snippetjavascriptTip
How can I clone an array in JavaScript?
Viewed 0 times
javascriptclonehowcanarray
Problem
JavaScript provides quite a few ways to clone an array, most of which are pretty similar in terms of performance and results. Here's a quick rundown of some of the available options.
ES6 introduced the spread operator (
Similarly to the spread operator,
Looking into one of the more unorthodox options,
ES6 introduced the spread operator (
...), which provides probably the easiest and most common way to create a shallow clone of an array.Array.from() has a very powerful API that can be used for many different things, including creating a copy of an array.Similarly to the spread operator,
Array.prototype.slice() can be used to create a shallow copy of an array.Looking into one of the more unorthodox options,
Array.prototype.map() can be used to map each element of an array to itself to create a new array.Solution
let x = [1, 2, 3, 4];
let y = [...x];Array.from() has a very powerful API that can be used for many different things, including creating a copy of an array.Similarly to the spread operator,
Array.prototype.slice() can be used to create a shallow copy of an array.Looking into one of the more unorthodox options,
Array.prototype.map() can be used to map each element of an array to itself to create a new array.Similarly,
Array.prototype.filter() can be used to return true for each and every element, resulting in a new array with all of the original array's elements.Finally,
Object.assign() can be used in the exact same way as it's used to create a clone of an object, but for an array instead.<baseline-support featureId="structured-clone">
Code Snippets
let x = [1, 2, 3, 4];
let y = [...x];let x = [1, 2, 3, 4];
let y = Array.from(x);let x = [1, 2, 3, 4];
let y = x.slice();Context
From 30-seconds-of-code: copy-array
Revisions (0)
No revisions yet.