;

Javascript Array - from() Method


Tutorialsrack 09/10/2022 Jquery Javascript

In this article, you will learn about the javascript Array built-in method Array.prototype.from(). How does this method work in javascript? 

Array.prototype.from()

This Array.prototype.from() method creates a new, shallow-copied Array instance from an iterable or array-like object. And it returns a new Array instance.

Syntax
array.from(arrayLike, mapFn(element [, index]) [,thisParameter]);

This method takes 3 parameters as given below:

  • arrayLike: This parameter holds an iterable or array-like object to convert to an array.
  • mapFn(Optional):  This function is used to call on every element of the array. The mapFn that is optional only receives two arguments (element, index) without the whole array, because the array is still under construction.
  • thisParameter(Optional): This parameter holds the context to be passed as this to be used while executing the mapFn function.

The Array.from() method never creates a sparse array. If the arrayLike object is missing some index properties, then they become undefined in the new array.

Here are some examples of Array.prototype.from() method:

Examples
//Array From String
console.log(Array.from('tutorialsrack'));
// Output => ["t", "u", "t", "o", "r", "i", "a", "l", "s", "r", "a", "c", "k"]


//Array from a Set
const set = new Set(['foo', 'bar', 'buzz', 'foo']);
console.log(Array.from(set));
// Output => ["foo", "bar", "buzz"]


//Array from a Set with empty slots 
const set1 = new Set(['foo', 'bar',, 'buzz', 'foo']);
console.log(Array.from(set1));
// Output => ["foo", "bar", undefined, "buzz"]


//Array from a Map
const map = new Map([[1, 2], [2, 4], [4, 8]]);
console.log(Array.from(map));
// Output => [[1, 2], [2, 4], [4, 8]]

const mapper = new Map([['1', 'a'], ['2', 'b']]);

//create an array of values from the map 
console.log(Array.from(mapper.values()));
// Output => ["a", "b"]

//create an array of indexes from the map 
console.log(Array.from(mapper.keys()));
// Output => ["1", "2"]

I hope this article will help you to understand the javascript Array built-in method Array.prototype.from()

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags