DEV Community

Toni Domazet
Toni Domazet

Posted on

2

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

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (0)

👋 Kindness is contagious

Explore this insightful post in the vibrant DEV Community. Developers from all walks of life are invited to contribute and elevate our shared know-how.

A simple "thank you" could lift spirits—leave your kudos in the comments!

On DEV, passing on wisdom paves our way and unites us. Enjoyed this piece? A brief note of thanks to the writer goes a long way.

Okay