In My Own Words: Array.from()

So I’ve just seen Array.from() today in a codewars study group I was giving. We wanted to make an array from 0 to x, and this function will do it for us!

So the first parameter, can either be an array, a string, or the length in the form of an object to set long the new Array should be.

Array.from({length: 5}) will give us an Array with a length of 5, all with undefined.

The optional second parameter is a map function,

(v, i) => i)

v is the value, which we will ignore, and instead will pass in a second parameter i which is the index, and if we return i in our map that will fill in each array with the current index, which will give us the range we wanted!

Array.from({length: 5}, (v, i) => i);
// [0, 1, 2, 3, 4]

Just to show you if we used the value, instead of the additional parameter index we could get this:

Array.from({length: 5}, v => v); 
// [undefined, undefined, undefined, undefined, undefined]

I am so happy to have learned this! It is sooo useful!

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright Loving to Code 2025
Tech Nerd theme designed by Siteturner