Using the from method

The Array.from method creates a new array from an existing one. For example, if we want to copy the array numbers into a new one, we can use the following code:

let numbers2 = Array.from(numbers); 

It is also possible to pass a function so that we can determine which values we want to map. Consider the following code:

let evens = Array.from(numbers, x => (x % 2 == 0)); 

The preceding code created a new array named evens, and a value true if in the original array the number is even, and false otherwise.

Get Learning JavaScript Data Structures and Algorithms - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.