3

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.

Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104
isemaj
  • 557
  • 1
  • 6
  • 19

5 Answers5

6

You can (shallow) copy the array before modifying it with .concat.

let result = [].concat(arr2);
// ... modify result...
AKX
  • 152,115
  • 15
  • 115
  • 172
  • As a sidenote: https://stackoverflow.com/q/17803586/1169798 . I'd also prefer `slice()` to make copies for readability reasons. – Sirko Jul 03 '18 at 08:01
3

You can use the "non destructive" function, AKA slice :
https://developer.mozilla.org/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);
Seblor
  • 6,947
  • 1
  • 25
  • 46
0

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 comment 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);
Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104
0

Try this. Slice function without parameter makes a (shallow) copy of an array .

let result = arr2.slice();
Joven28
  • 769
  • 3
  • 12
0

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];

LordTribual
  • 4,219
  • 2
  • 28
  • 38