How to Create a New Array from an Array in JavaScript?

Estimated read time 1 min read

There are several ways to create a new array from an existing array in JavaScript. Some of the common methods are:

  1. Using the slice() method: The slice() method creates a new array that contains a portion of the original array.

For example:

var originalArray = [1, 2, 3, 4, 5];
var newArray = originalArray.slice(1, 4);

console.log(newArray); // Output: [2, 3, 4]
  1. Using the map() method: The map() method creates a new array by transforming each element of the original array using a callback function.

For example:

var originalArray = [1, 2, 3, 4, 5];
var newArray = originalArray.map(function(element) {
  return element * 2;
});

console.log(newArray); // Output: [2, 4, 6, 8, 10]
  1. Using the filter() method: The filter() method creates a new array by filtering the elements of the original array based on a condition specified in a callback function.

For example:

var originalArray = [1, 2, 3, 4, 5];
var newArray = originalArray.filter(function(element) {
  return element % 2 === 0;
});

console.log(newArray); // Output: [2, 4]
  1. Using the spread operator (...): The spread operator allows you to create a new array from an existing array by spreading its elements.

For example:

var originalArray = [1, 2, 3, 4, 5];
var newArray = [...originalArray];

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

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply