Approaches 1: Using the Spread Operator (…)
The spread operator (…) is a concise syntax introduced in ES6 that allows us to expand iterable objects, like arrays, into individual elements. To copy an array using the spread operator, you simply spread the elements of the original array into a new array literal.
Syntax:
const copiedArray = [...originalArray];
Example: In this example, we will see the use of the spread operator.
const originalArray = [1, 2, 3, 4, 5];
const copiedArray = [...originalArray];
// Output: [1, 2, 3, 4, 5]
console.log(copiedArray);
Output
[ 1, 2, 3, 4, 5 ]
Copy Array Items into Another Array in JavaScript
We will see how to copy array items into another array in JavaScript. This operation is valuable when you need to generate a new array containing either identical or a subset of elements from an original array.
These are the following ways to solve this problem:
Table of Content
- Using the Spread Operator (…)
- Using slice() Method
- Using apply() Method
- Using Array.concat() Method
- Using push() Method
- Using map() Method
Contact Us