Copy Items Into a New Array in JavaScript
In this tutorial, we’ll explore multiple ways to copy elements from an existing array into a new array, covering scenarios like duplicating a list to avoid direct mutation or working with filtered data.
Method 1: Using the Spread Operator (...)
This is the most modern and preferred method to copy all items from one array to another. The spread operator unpacks elements of an array into a new one, maintaining a shallow copy.
const original = ["apple", "banana", "cherry"];
const copied = [...original];
console.log(copied);
["apple", "banana", "cherry"]
Method 2: Using slice()
The slice() method returns a shallow copy of a portion of an array. If no arguments are passed, it returns a copy of the entire array.
const original = ["Item 1", "Item 2", "Item 3"];
const copied = original.slice();
console.log(copied);
["Item 1", "Item 2", "Item 3"]
Method 3: Using Array.from()
Array.from() creates a new, shallow-copied Array instance from an array-like or iterable object. It's a versatile tool that’s also useful when transforming values during copy.
const original = ["Hello", "World", "!"];
const copied = Array.from(original);
console.log(copied);
["Hello", "World", "!"]
Method 4: Using map() to Copy With Transformation
If you want to copy items while also modifying them, map() is a perfect fit. It creates a new array populated with results of calling a function on every element.
const original = ["Item 1", "Item 2", "Item 3"];
const copied = original.map(item => "Item: " + item);
console.log(copied);
["Item: Item 1", "Item: Item 2", "Item: Item 3"]
Comparison Table
| Method | Mutable? | Transforms Items? | Shallow Copy? |
|---|---|---|---|
[...array] |
No | No | Yes |
slice() |
No | No | Yes |
Array.from() |
No | Optional | Yes |
map() |
No | Yes | Yes |
Comments
Loading comments...