Introduction to flat and flatMap in javascirpt
In this tutorial, we will learn about how to use and when to use the Flat() and FlatMap() method in JavaScript.
flat and flatMap method was introduced in es2019
flat():
The flat() method makes nested array into a single array
For example,
We have an nested array as follows:
const arr = [[1, 2, 3], [4, 5, 6], 7, 8];
Now we can convert into one single array using flat method as follows:
const result = arr.flat();
console.log(result);
//const result = arr.flat();
By default, the Flat method goes only one level deep,means it will not flat nested of nested array
However, We can change the depth as follows:
arr.flat(2);
flatMap():
The flatMap() method essential combines map and flat map method which is better for performance.
Note: flatMap goes only one level deep we can't change it
For Example,
Suppose we have two arrays as follows:
const user = ['john', 'james', 'ali'];
const ages = [18, 45, 12];
Now we want to create new with the combination of users and theri ages, we can do this uusing flatmap as follows:
const mappedOnly = user.map((animal, index) => [animal, noises[index]]);
console.log(mappedOnly);
//[["john",18],["james",45],["ali",12]]
const mappedwithflat = user.flatMap((animal, index) => [animal, ages[index]]);
console.log(mappedwithflat);
//["john", 18, "james", 45, "ali", 12]