Is there any way to make the splice()
non-destructive?
What I need to do is to retain the arr2
as it is after I call the function.
function foo(arr1, arr2, n) {
let result = arr2;
result.splice(n, 0, ...arr1.slice(0, arr1.length));
console.log(arr2);
}
foo(["I'm", "not", "done"], ["sorry", "yet"], 1);
Although it returns sorry,I'm,not,done,yet
which is what I want but the elements of arr2
shouldn't change.
Is there any way to make the splice()
non-destructive?
What I need to do is to retain the arr2
as it is after I call the function.
function foo(arr1, arr2, n) {
let result = arr2;
result.splice(n, 0, ...arr1.slice(0, arr1.length));
console.log(arr2);
}
foo(["I'm", "not", "done"], ["sorry", "yet"], 1);
Although it returns sorry,I'm,not,done,yet
which is what I want but the elements of arr2
shouldn't change.
-
4
Use
slice
instead ofsplice
. Same syntax, but not "destructive". – Seblor Commented Jul 3, 2018 at 7:57
5 Answers
Reset to default 6You can (shallow) copy the array before modifying it with .concat
.
let result = [].concat(arr2);
// ... modify result...
You can use the "non destructive" function, AKA slice
:
https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
Here's a SO question with the difference between slice and splice : JavaScript Array splice vs slice
The syntax is the exact same, so you just have to remove one letter
function foo(arr1, arr2, n) {
let result = arr2;
result.slice(n, 0, ...arr1.slice(0, arr1.length));
console.log(arr2);
}
foo(["I'm", "not", "done"], ["sorry", "yet"], 1);
Try this. Slice function without parameter makes a (shallow) copy of an array .
let result = arr2.slice();
Inside your function you can also use the spread operator (in case you are using ES2015) to create a copy of arr2
:
let result = [...arr2];
Option 1:
You can use array.concat().
Please find below example:
function foo(arr1, arr2, n) {
let result = [].concat(arr2);
result.splice(n, 0, ...arr1.slice(0, arr1.length));
console.log(arr2);
console.log(result);
}
foo(["I'm", "not", "done"], ["sorry", "yet"], 1);
Option 2:
Using array.slice() mentioned in ment above by @Seblor like this let result = arr2.slice();
Example below:
function foo(arr1, arr2, n) {
let result = arr2.slice();
result.splice(n, 0, ...arr1.slice(0, arr1.length));
console.log(arr2);
console.log(result);
}
foo(["I'm", "not", "done"], ["sorry", "yet"], 1);