In this section of code:
arr1 gets spliced exactly the same as arr2 - why does this happen?
I know that splice changes the original array but I would think that its original array in this case is arr2 and not arr1…
In this case,
arr2 are the same array. You’d need to copy the array to prevent this.
So when assigning one array to another they become one?
So should I just
slice() for this kind of thing or is there a better way to copy the array?
There is a lot of good discussion here.
arr1 is an array of literal values (boolean, number, or string), you can use any deep copy technique discussed above, where the spread operator
... has the highest performance.
// Highest performance for deep copying literal values
arr2 = [...arr1];
// Any of these techniques will deep copy literal values as well,
// but with lower performance.
arr2 = arr1.slice();
arr2 = arr1.splice(0);
arr2 = arr1.concat();
arr2 = JSON.parse(JSON.stringify(arr1));
arr2 = $.extend(true, , arr1); // jQuery.js needed
arr2 = _.extend(arr1); // Underscore.js needed
arr2 = _.cloneDeep(arr1); // Lo-dash.js needed
arr2 = copy(arr1); // Custom-function needed - as provided above
I wouldn’t call it a bummer. Passing arrays by value has a serious performance impact. If your arrays are not tiny, you want pass by reference.