How to use Array.from() In Javascript
This method is used to create a new,shallow-copied array from an array-like or iterable object.
Syntax:
Array.from(arrayLike, (element) => { /* ... */ } )
Example: Array.from() is called which lets us map an empty array of size 5 to an array with some elements inside. The second argument is a callback that returns 0 which is used to fill the array.
Javascript
const arr = Array.from(Array(5), () => 0) console.log(arr); |
Output
[ 0, 0, 0, 0, 0 ]
The same result can be obtained by passing an object with the length property using the Array.from() method.
Javascript
const arr = Array.from({ length: 5 }, () => 0) console.log(arr); |
the
Output
[ 0, 0, 0, 0, 0 ]
Creating a Zero-Filled Array in JavaScript
A zero-filled array is an array whose value at each index is zero.
Below are the methods used for creating a Zero-Filled Array in JavaScript:
Table of Content
- Array.prototype.fill
- Using Apply() and Map()
- Using Array.from()
- Using for loop
- Using Lodash _.fill() Method