How do I create a new array from an existing array in JavaScript?
Alex K
alex k profile pic

In JavaScript, there are several ways to create a new array from an existing array. Let's explore some common methods: 1. Using the slice() method: Theslice() method can be used to create a new array that contains a shallow copy of elements from the original array. By providing no arguments toslice(), you can create a copy of the entire array. Here's an example:

1
2
3
4
5

   var originalArray = [1, 2, 3, 4, 5];
   var newArray = originalArray.slice();
   console.log(newArray); // Output: [1, 2, 3, 4, 5]
   

In this code snippet,slice() is called without any arguments, creating a new array (newArray) that contains a copy of all elements from theoriginalArray. 2. Using the concat() method: Theconcat() method is used to merge two or more arrays and create a new array as a result. By passing the original array as an argument toconcat(), you can create a new array that contains all elements from the original array. Here's an example:

1
2
3
4
5

   var originalArray = [1, 2, 3, 4, 5];
   var newArray = [].concat(originalArray);
   console.log(newArray); // Output: [1, 2, 3, 4, 5]
   

In this code snippet,concat() is called with an empty array ([]) and theoriginalArray as arguments, resulting in a new array (newArray) that contains all elements from theoriginalArray. 3. Using the spread operator: ES6 introduced the spread operator (...), which allows you to expand elements from an array or other iterable objects. You can use the spread operator to create a new array by spreading the elements of the original array into the new array. Here's an example:

1
2
3
4
5

   var originalArray = [1, 2, 3, 4, 5];
   var newArray = [...originalArray];
   console.log(newArray); // Output: [1, 2, 3, 4, 5]
   

In this code snippet, the spread operator...originalArray spreads the elements of theoriginalArray into the new array (newArray), creating a copy of all elements. These are some common approaches to create a new array from an existing array in JavaScript. Choose the method that best suits your coding style and requirements. Remember that these methods create a new array rather than modifying the original array.