=) to copy the values. It will only copy the reference to the original object and not the elements of the array.
Array.slice() method, the Array.from() method, or the spread operator (
...) to duplicate an array. You don't need to use a loop to iterate over all elements of an array and push them into another array.
Note: If you want to create a deep clone of an array, take a look at this article.
The simplest and quickest way to copy the contents of an existing array into a new array is by using the slice() method without any parameter:
const fruits = ['🍑', '🍓', '🍉', '🍇', '🍒']; // clone `fruits` using `slice()` const moreFruits = fruits.slice(); console.log(moreFruits); // ['🍑', '🍓', '🍉', '🍇', '🍒']
In the above code, the
slice() method creates a shallow copy of the original array, and not a deep clone. The original array remains unchanged. If the original array contains objects, only their references will be copied to the new array.
Array object from an array-like or iterable object.
Here is an example:
const fruits = ['🍑', '🍓', '🍉', '🍇', '🍒']; // clone `fruits` using `Array.from()` const moreFruits = Array.from(fruits);
Array.from() method was introduced in ES6, so it only works in modern browsers. But you can use a polyfill to push the browser support way back to IE6.
The spread operator (
const fruits = ['🍑', '🍓', '🍉', '🍇', '🍒']; // clone `fruits` using spread operator const moreFruits = [...fruits];
Array.slice(), the spread operator creates a shallow copy of the original array. It only goes one-level down when cloning an array. If you're coping multi-dimension array or an array that contains objects, you have to look for other alternatives.
Array.concat() method is originally used for merging two arrays into one, you can use it for cloning an array as well:
const fruits = ['🍑', '🍓', '🍉', '🍇', '🍒']; // merge `fruits` with emtpy array to // create a new array const moreFruits = .concat(fruits);