DEV Community

Cover image for 7 Amazing use cases of Array.from() method in JavaScript
Subaash
Subaash

Posted on

7 Amazing use cases of Array.from() method in JavaScript

The Array.from() method creates a shallow-copied array instance from an array like object or an iterable. The iterable object could be an array, a string, a set, an object or anything with an iterable property.

Syntax:

Array.from(iterable, mapFunction, thisArg)
where,

  • iterable: the object to convert into an array

  • mapFunction (optional): A function to call on each element of the array. The mapFunction accepts two parameters as any regular Javascript map function does. The first parameter is the current element and the second one its index in the array.

  • thisArg (optional): An object to pass as this when using the map function.
    Let's look at their use cases in brief

1. Generate numbers up to a specific range:

The traditional method of generating numbers up to a specific range is always to use loops. But the Array.from() method is a one-liner which does the same job as the Javascript loops in this case.

// The traditional method: 
const numberCount = [];
for( let i=0; i < 5; i++){
    numberCount.push( i+1 )
}
console.log(numberCount) // Output: [ 1, 2, 3, 4, 5 ]

// Using Array.from() method to do the same job: 
Array.from( { length: 5 }, (_, index)=> index+1 )
// Output: [ 1, 2, 3, 4, 5 ]
Enter fullscreen mode Exit fullscreen mode

2. Creating a Matrix:

While working with mathematical concepts or engaging in complex use cases, dealing with multi-dimensional arrays can be a cumbersome task, especially during the creation phase. To create one, we use nested for loops, and a small mistake in the logic can end up in vain. But the task is made easier with Array.from() method and it is easy to debug as well.

// Create a grid of Default value
let defaultValue = 0;
let grid = Array.from({ length: 3 }, () => Array.from({ length: 3 }, () => defaultValue ));
// Output: [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]
// Create a grid with numbers in the increasing order
let grid = Array.from({ length: 3 }, () => Array.from({ length: 3 }, (_, i) => i+1));
// Output: [ [ 1, 2, 3 ], [ 1, 2, 3 ], [ 1, 2, 3 ] ]
Enter fullscreen mode Exit fullscreen mode

3. Mapping object properties into arrays

If you wish to map either the keys or values of an object into an array, it is better to use Array.from() in addition to Objectmethods

const user = { name: 'Ram', age: 23, city: 'Chennai' }
const userInfo = Array.from( Object.values(user) )
// Output: [ 'Ram', 23, 'Chennai' ]
Enter fullscreen mode Exit fullscreen mode

4. Creating an HTML nodelist

let listItems = Array.from( { length: 5 }, (item, index)=>{
    const item = document.createElement('li');
    item.textContent = index + 1;
    return item
})
// Output: NodeList [ <li>, <li>, <li>, <li>, <li> ]
Enter fullscreen mode Exit fullscreen mode

5. Converting NodeList into an Array

In addition to the previous use case at 4, the DOM items could be converted back into arrays using Array.from() method

const listItems = document.querySelectorAll('.listItems')
const listItemsArray = Array.from( listItems )
Enter fullscreen mode Exit fullscreen mode

6. Customizing array elements

Customizing array elements is made easier with Array.from() javascript method. The Array.from() method creates a shallow copy of the array being passed and manipulates each element while creating a new array. Let's get it clear from the following example.

const numbers = [ 1, 2, 3, 4, 5 ]
const multiplyByTwo = Array.from( numbers, (number)=>number*2 )
// Output: [ 2, 4, 6, 8, 10 ]

// Strings can be manipulated as well
const tags = [ webDev, grateful, mentorship, frontend ] 
const twitterTags = Array.from( tags, ( tag, index )=>'#'+tag )
//Output: [ '#webDev', '#grateful', '#mentorship', '#frontend' ]
Enter fullscreen mode Exit fullscreen mode

7. Creating a character frequency map

Array.from() can be used to find how frequently a letter occurs in a sentence or in a given passage. We could achieve this by simply utilising some basic JavaScript functions and methods.

const greet = 'Hello, world!';
const freqMap = Array.from( greet, ( letter )=>({[letter]: greet.split( letter ).length-1 }))
// Output: 
[
  { H: 1 },   { e: 1 },
  { l: 3 },   { l: 3 },
  { o: 2 },   { ',': 1 },
  { ' ': 1 }, { w: 1 },
  { o: 2 },   { r: 1 },
  { l: 3 },   { d: 1 },
  { '!': 1 }
]
Enter fullscreen mode Exit fullscreen mode

These are some use cases of JavaScript's Array.from() method. Please note that, some of the use cases could efficiently be solved using alternate methods available within Javascript, though I wanted to showcase the abilities of this method. For details about the basics and more basic examples, visit the official MDN docs page.

Top comments (6)

Collapse
 
mainarthur profile image
Arthur Kh

Hey! Thank you for article!
Just want to add Object.value already returns Array so you don't have to convert it to Array using Array.from
Image description
It's more used with Maps because Map.prototype.values doesn't return an array, it returns map iterator which could be converted to array using Array.from

const map = new Map([
  [1, 2],
  [2, 4],
  [4, 8],
]);
Array.from(map);
// [[1, 2], [2, 4], [4, 8]]

const mapper = new Map([
  ["1", "a"],
  ["2", "b"],
]);
Array.from(mapper.values());
// ['a', 'b'];

Array.from(mapper.keys());
// ['1', '2'];
Enter fullscreen mode Exit fullscreen mode
Collapse
 
subaash_b profile image
Subaash

You are absolutely correct. Thank you for your opinion. Future articles will be free of contradictions. Have a nice day 🙂❤️.

Collapse
 
codingjlu profile image
codingjlu

Nice article. Just wanted to say, the character frequency map isn't very efficient (unnecessary quadratic time complexity) and doesn't end up being in a usable form and has multiple same entries. Something simple using Array#reduce works, e.g.:

const freqMap = str => str.split("").reduce(
  (map, char) => (map[char] ??= 0, map[char]++, map), {}
)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
subaash_b profile image
Subaash

Thank you for your feedback. I appreciate the suggestion and accept the same. I just wanted to demonstrate some intermediary use cases of Array.from() method. Indeed Array.reduce() is the more efficient approach. I'll consider incorporating that improvement in the future articles. Have a nice day.!

Collapse
 
manchicken profile image
Mike Stemle

I wish people would stop writing this exact same article every week.

Collapse
 
subaash_b profile image
Subaash

I wanted to make the article as unique as possible. But if you find the topic boring, I apologise for the same.