There are several ways to create a new array from an existing array in JavaScript. Some of the common methods are:
- Using the
slice()
method: Theslice()
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]
- Using the
map()
method: Themap()
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]
- Using the
filter()
method: Thefilter()
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]
- 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]
+ There are no comments
Add yours