Returning an array without a removed element? Using splice() without changing the array?
You want slice
:
Returns a one-level deep copy of a portion of an array.
So if you
a = ['one', 'two', 'three' ];
b = a.slice(1, 3);
Then a
will still be ['one', 'two', 'three']
and b
will be ['two', 'three']
. Take care with the second argument to slice
though, it is one more than the last index that you want to slice out:
Zero-based index at which to end extraction.
slice
extracts up to but not includingend
.
as suggested by the answer below, here is a code snapshot
var myArray = ["one", "two", "three"];
var cloneArray = myArray.slice();
myArray.splice(1, 1);
console.log(myArray);
console.log(cloneArray);
Use this:
function spliceNoMutate(myArray,indexToRemove) {
return myArray.slice(0,indexToRemove).concat(myArray.slice(indexToRemove+1));
}