You can simply use the slice() method to create a copy of a JavaScript array that behaves independently. This method returns a shallow copy of a portion of an array into a new array.
Let's try out the following example to understand how it basically works:
// Original array
var array1 = ["red", "green", "blue"];
// Making a copy
var array2 = array1.slice();
// Adding a new element to copied array
array2.push("pink");
console.log(array2); // Prints: ['red', 'green', 'blue', 'pink']
console.log(array1); // Prints: ['red', 'green', 'blue']
Alternatively, in ES6 you can easily make an independent copy of an array by using the spread operator (...). Let's take a look at an example to understand how it actually works:
// Original array
var array1 = ["red", "green", "blue"];
// Copying the array
var array2 = [...array1];
// Adding a new element to copied array
array2.push("pink");
console.log(array2); // Prints: ['red', 'green', 'blue', 'pink']
console.log(array1); // Prints: ['red', 'green', 'blue']
Use the
slice()MethodYou can simply use the
slice()method to create a copy of a JavaScript array that behaves independently. This method returns a shallow copy of a portion of an array into a new array.Let's try out the following example to understand how it basically works:
Alternatively, in ES6 you can easily make an independent copy of an array by using the spread operator (...). Let's take a look at an example to understand how it actually works:
need an explanation for this answer? contact us directly to get an explanation for this answer