Saturday, December 1, 2018

Understanding Array.from() in JavaScript

This tutorial explains how to use Array.from() function in javascript. The Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object.

Syntax :
Array.from(object, mapFunction, thisValue)

Parameter          Description
object                    Required. The object to convert to an array
mapFunction   :  Optional. A map function to call on each item of the array
thisValue          :        Optional. A value to use as this when executing the mapFunction

Understanding Array.from() in JavaScript


Convert String to Array :

var a = Array.from('Skptricks');
console.log(a)

Output:-
------------------------
> Array ["S", "k", "p", "t", "r", "i", "c", "k", "s"]

Convert Set to Array :

var a = Array.from(new Set(['A', 'B', 'CC', 'D'])); 
console.log(a)

Output:-
------------------------
> Array ["A", "B", "CC", "D"]

Convert Map to Array :

var a = Array.from(new Map([['a', 1],['b', 2],['c', 3],['d', 4]])); 
console.log(a)

Output:-
------------------------
> Array [Array ["a", 1], Array ["b", 2], Array ["c", 3], Array ["d", 4]]

Generate a sequence of numbers : 

var a = Array.from({length: 5}, (v, i) => i);
console.log(a)

Output:-
------------------------
> Array [0, 1, 2, 3, 4]

Using arrow functions :

Using an arrow function as the map function to manipulate the elements.
var a = Array.from([1, 2, 3], x => x + x);      
console.log(a)

Output:-
------------------------
> Array [2, 4, 6]

This is all about Array.from() in JavaScript. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

No comments:

Post a Comment