patternjavascriptCritical
Copy array by value
Viewed 0 times
arraycopyvalue
Problem
When copying an array in JavaScript to another array:
I realized that
var arr1 = ['a','b','c'];
var arr2 = arr1;
arr2.push('d'); // Now, arr1 = ['a','b','c','d']I realized that
arr2 refers to the same array as arr1, rather than a new, independent array. How can I copy the array to get two independent arrays?Solution
Use this:
Basically, the
Also note that:
For references, strings and numbers (and not the actual object),
Primitives such as strings and numbers are immutable, so changes to the string or number are impossible.
let oldArray = [1, 2, 3, 4, 5];
let newArray = oldArray.slice();
console.log({newArray});
Basically, the
slice() operation clones the array and returns a reference to a new array.Also note that:
For references, strings and numbers (and not the actual object),
slice() copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.Primitives such as strings and numbers are immutable, so changes to the string or number are impossible.
Context
Stack Overflow Q#7486085, score: 3157
Revisions (0)
No revisions yet.