0

I've searched up this question, and everywhere people seem to recommend to use array.splice(). However, splice is inplace, and, for example, in my javascript console editor.

Array splicing

Everywhere I seem to search, people say that splice does NOT mutate the original array, but that is clearly not the case. Now, I'm sure I will find another way to do what I want, but what is the proper way to make a copy of a piece of an array without affecting the original array?

  • slice does not mutate the original array. splice mutates the array. The names are bit similar – Utsav Patel Apr 22 '20 at 03:48
  • First line on [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice): "The `splice()` method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place." You need to use `slice()` instead. – Robby Cornelissen Apr 22 '20 at 03:49

2 Answers2

2

You can use slice(), see below:

let x = [1, 2, 3, 4, 5]

console.log(x);

let sliced = x.slice(0, 2);

console.log(x);
console.log(sliced);

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included) where begin and end represent the index of items in that array. The original array will not be modified.

Luís Ramalho
  • 10,018
  • 4
  • 52
  • 67
0

Make a copy of the array using the spread operator and then you can use splice or whatever.

let arr = [1, 2, 3, 4, 5];

let newArr = [...arr];

console.log(newArr);

// newArr.splice(......)
mph85
  • 1,276
  • 4
  • 19
  • 39