DEV Community

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

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

Subaash on December 05, 2023

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...
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.