Q:

How to Copy Array by Value in JavaScript

0

How to Copy Array by Value in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the slice() Method

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Remove Text from a String in JavaScript... >>
<< How to Convert a Unix Timestamp to Time in JavaScr...