JavaScript Array from() method is used to create a new array instance from an array-like or iterable object(Map or Set). This method is particularly useful when working with various data structures and array-like objects.
Syntax
Array.from(arrayLike[, mapFn[, thisArg]])
Parameters
- arrayLike(required): It is an array-like or iterable object to convert to an array.
- mapFn(Optional): Map function to call on every array element.
- thisArg(Optional): Value to use as this when executing mapFn.
Return Value
Returns a new Array instance.
Visual Representation
Example 1: How to Use Array from() Method
let str = 'Italy';
let strArr = Array.from(str);
console.log(strArr);
Output
[ 'I', 't', 'a', 'l', 'y' ]
Example 2: Create an array from a set
let countries = new Set(['Italy', 'USA', 'UK']);
console.log(Array.from(countries));
Output
[ 'Italy', 'USA', 'UK' ]
Example 3: Array from an array-like object
function arrFrm(){
return Array.from(arguments);
}
let arr = arrFrm(7, 14, 28);
console.log(arr);
Output
[ 7, 14, 28 ]
In the above example, arguments object inside the function is an array-like object that represents the arguments passed to the function. Then it converts this array-like object into a real array.
Example 4: Using with a mapping function
let data = [7, 8, 9];
let final = Array.from(data, x => x * x);
console.log(final);
Output
[ 49, 64, 81 ]
Browser compatibility
- Google Chrome 45
- Microsoft Edge 12
- Mozilla Firefox 32
- Safari 9
- Opera 32
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.