The Array.from
function is pretty useful to convert array like structures in a proper array,
I think the most used case is converting a list of HTML elements to array.
Take this example:
jsconst titleElements = document.querySelectorAll('h1');const titles = Array.from(titleElements).map(element => element.textContent);
This example extracts the content of h1
tags from a html page.
That's nice, but there's a way to improve this code by making use of a lesser known feature, the callback we can pass to Array.from
allow us to change the content of each element in the soon to be array, the same thing the map
method is doing.
This is a rewrite of the previous snippet
jsconst titleElements = document.querySelectorAll('h1');const titles = Array.from(titleElements, element => element.textContent);
Now we eliminated the need for .map
, since Array.from
alone accomplishes the same desired output.
We can also replace .map
access in an array for Array.from
.
Take this example, you have an array of cart products and want to find out the most expensive price in the list
jsconst products = [{productId: 3604356263131261,productName: 'Desk',productPrice: 413.2,},{productId: 5445735849133131,productName: 'Chair',productPrice: 253.17,},...];const mostExpensive = Math.max(...products.map(product => product.productPrice),);console.log(mostExpensive);
In this example we create a new array with the prices, and then destructure it and pass to the Math.max function, to get the highest price.
We can do pretty much the same using Array.from
.
jsconst mostExpensive = Math.max(...Array.from(products, product => product.productPrice),);console.log(mostExpensive);
The callback for both Array.from
and Array.prototype.map
is pretty similar,
except that you don't get access to the full array in the Array.from
.
We can verify this by logging the parameters received.
js// Array.prototype.mapproducts.map((...args) => console.log(args));// Array.fromArray.from(products, (...args) => console.log(args));
The Array.prototype.map
one will receive three parameters, the current item, the index and the full array.
The Array.from
callback has no access to the full array.
That's it, remember to make use of the Array.from
callback from now on.