-2

so i am having a problem using javascript array splice where it changes the orginal array like

let arr1 = [1,2,3,4,5]
for(i = 0; i < 5; i++){arr1.splice(i,1);}

in this above example , the arr1 gets changed after every iteration like :- [2,3,4,5]...[3,4,5]..etc

what i want to achive is :-

let arr1 = [1,2,3,4,5];
for(i = 0; i < 5; i++){
    let arr2 = arr1.splice(i,1);
}

the result of this should give arr1 as [1,2,3,4,5] in all iteration ... but arr2 as [2,3,4,5]...[3,4,5]..etc ..... Basically, i want the splice function to not manipulate the original array but give the result in a new array and the original array remains the same during all iteration... is there any way to do this?

Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
Prastut Dahal
  • 27
  • 1
  • 6

2 Answers2

1

If you want to return those partial arrays within common array (overwriting single variable as it is done by your code now doesn't make much sense) you may use Array.prototype.slice() along with Array.prototype.map()

const src = [1,2,3,4,5],
      res = src.map((_,i,s) => s.slice(i))
      
console.log(JSON.stringify(res))
.as-console-wrapper{min-height:100%;}

If you need to do some further stuff with those partial arrays, you may either modify your initial code, like that:

let arr1 = [1,2,3,4,5];
for(i = 0; i < 5; i++){
    let arr2 = arr1.slice(i+1)
    //log stringified arr2
    console.log(JSON.stringify(arr2))
}
.as-console-wrapper{min-height:100%;}

Or, make use of Array.prototype.forEach :

let arr1 = [1,2,3,4,5];
arr1.forEach((_,i,s) => {
  const arr2 = s.slice(i+1)
  // log stringified arr2
  console.log(JSON.stringify(arr2))
 
})
.as-console-wrapper{min-height:100%;}
Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
1

You could slice the array with index plus one.

let arr1 = [1, 2, 3, 4, 5];
for (let i = 0; i < 5; i++) {
    console.log(...arr1.slice(i + 1));
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392