Array.from in Javascript

The Array.from() method in JavaScript is used to create a new, shallow-copied array from an iterable object or an array-like object. It takes an iterable or array-like object as its first argument and an optional mapping function as its second argument. The mapping function is applied to each element in the iterable or array-like object.

Here’s the basic syntax:

Array.from(iterable, mapFunction);
  • iterable: The iterable or array-like object to convert into an array.
  • mapFunction (optional): A mapping function to be applied to each element of the iterable. It’s similar to the map() method.

Examples

Create an array from a string:

const str = 'hello';
const charArray = Array.from(str);

console.log(charArray); // Output: ['h', 'e', 'l', 'l', 'o']

Create an array from a set:

const set = new Set([1, 2, 3]);
const arrayFromSet = Array.from(set);

console.log(arrayFromSet); // Output: [1, 2, 3]

Using a mapping function:

const arrayFromRange = Array.from({ length: 5 }, (_, index) => index + 1);

console.log(arrayFromRange); // Output: [1, 2, 3, 4, 5]

In the last example, the Array.from() method is used to create an array of numbers from 1 to 5 using the length property of an object and a mapping function.

The _ is a convention to indicate that the first parameter (which is not used) is intentionally ignored, and index represents the index of the current element.

It’s important to note that Array.from() is often used for converting iterable objects (like strings, sets, maps) or array-like objects (like the arguments object or NodeList) into a standard array. The second argument, mapFunction, is optional and can be used for additional transformations during the conversion process.

Array of first 100 numbers:

let frist100Num = Array.from({length: 100}, (el, idx)=> idx)

Array of 100 images from placeholder

let hundredImages = Array.from(
    { length: 100 },
    (_, i) => `https://placeimg.com/640/480/any?image=${i}`
  );


Posted

in

by

Tags:

Comments

Leave a Reply

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