What is array-from?
The npm package 'array-from' provides a utility function for creating arrays from array-like or iterable objects. This is particularly useful for converting objects that resemble arrays but do not have the full functionality of an Array, such as NodeLists or arguments objects, into true JavaScript arrays.
What are array-from's main functionalities?
Creating arrays from array-like objects
Converts an array-like object (object with properties indexed from 0 and a length property) into a true array.
const arrayFrom = require('array-from');
const arrayLike = {0: 'hello', 1: 'world', length: 2};
const newArray = arrayFrom(arrayLike);
console.log(newArray); // ['hello', 'world']
Creating arrays from iterable objects
Converts an iterable object (like Set or Map) into a true array, allowing for easier manipulation and access to array methods.
const arrayFrom = require('array-from');
const set = new Set(['foo', 'bar', 'baz']);
const newArray = arrayFrom(set);
console.log(newArray); // ['foo', 'bar', 'baz']
Other packages similar to array-from
to-array
Similar to 'array-from', 'to-array' converts array-like or iterable objects into true arrays. The difference lies in the implementation details and additional utility functions that 'to-array' might offer, making it suitable for different use cases depending on the specific needs of the developer.
array-from
A ponyfill for the ES 2015 Array.from()
.
* Ponyfill: A polyfill that doesn't overwrite the native method.
* ES 2015: The new name for ES6 that nobody expected.
Modeled after revision 22 of the ES 2015 spec. Credits for the implementation go to the amazing folks of the MDN. See the original here.
Installation
$ npm install array-from
Usage
Recommended:
var arrayFrom = require('array-from');
function () {console.log(
arrayFrom(arguments).map(require('1-liners/increment'))
);}(1, 2, 3);
You can also use it as a classical polyfill. It’s not recommended, but sometimes practical:
if (!Array.from) Array.from = require('array-from');
function () {console.log(
Array.from(arguments).map(require('1-liners/increment'))
);}(1, 2, 3);
License
MIT © Studio B12 GmbH