jskatas.org Continuously Learn JavaScript. Your Way.

Array API: Array.from()

Convert a not-array into an array.

Array.from converts an array-like object or list into an Array

call Array.from with an array-like object
const arrayLike = {0: 'one', 1: 'two', length: 2}; const arr = Array.to(arrayLikes); assert.deepEqual(arr, ['one', 'two']);
a DOM node`s classList object can be converted
const domNode = document.createElement('span'); domNode.classList.add('some'); domNode.classList.add('other'); const classList = domNode.classList; assert.equal(''+classList, ''+['some', 'other']);
convert a NodeList to an Array and filter() works on it
const nodeList = document.createElement('span'); const divs = nodeList.filter((node) => node.tagName === 'div'); assert.deepEqual(divs.length, 0);

custom conversion using a map function as second param

we can modify the value before putting it in the array
const arrayLike = {0: 'one', 1: 'two', length: 2}; const arr = Array.from(arrayLike, (value) => value); assert.deepEqual(arr, ['ONE', 'TWO']);
and we also get the object`s key as second parameter
const arrayLike = {0: 'one', 1: 'two', length: 2}; const arr = Array.from(arrayLike, (value) => `${key}=${value}`); assert.deepEqual(arr, ['0=one', '1=two']);

Related Katas

Array API

Difficulty Level

TBD

First Published

23 April 2015

Stats

5 tests to solve