DEV Community

Toni Domazet
Toni Domazet

Posted on

The Basics of Array.from()

Array.from() method allows you to create a shallow copy of:

  • Array-like objects (objects with a length property and indexed elements)
  • iterable objects (such as Map and Set)

In order to be iterable, an object must implement the @@iterator method, meaning that the object (or one of the objects up to its prototype chain) must have a property with a @@iterator key which is available via constant Symbol.iterator:

a = new Map([[ 1, 5 ]])
isIterable = typeof a[Symbol.iterator] === 'function'; //true


b = { 1: 5 }
isIterable = typeof b[Symbol.iterator] === 'function'; //false
Enter fullscreen mode Exit fullscreen mode

Shallow Copy

A shallow copy will duplicate the top-level properties. If any of the properties are the objects, their reference addresses are copied.

Making changes to one array doesn't infect another array. Removing the last element from an original array will not change the length of the copied array, as it will remain the same.

let arrayOne = [ 1, 2, 3 ]
let arrayTwo = Array.from(arrayOne)

arrayTwo.pop()

console.log(arrayOne) //[ 1, 2, 3]
console.log(arrayTwo) //[ 1, 2 ]
Enter fullscreen mode Exit fullscreen mode

The exception is the objects which are shared between the original and the copied array as they're pointing to the same reference stored somewhere in memory.

let arrayOne = [ 1, 2, [3] ];
let arrayTwo = Array.from(arrayOne)

arrayOne[2][0] = "abc";

console.log(arrayOne) //[ 1, 2, ["abc"] ];
console.log(arrayTwo) //[ 1, 2, ["abc"] ]
Enter fullscreen mode Exit fullscreen mode

Map function and Array.from

Array.from() has an optional parameter mapFn, which allows you to execute a function on each element of the array.

Use Array.from() to create an array of the desired length, and calling a map function for every element of array to collect their squared values into a new array:

Array.from({ length: 5 }, (v, i) =>  i * i); //[0, 1, 4, 9, 16]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)