Flat And flatMap In JavaScript

Flat And flatMap In JavaScript: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the Flat And flatMap In JavaScript.

Flat And flatMap In JavaScript

flat() and flatMap() are two array methods in JavaScript that allow you to manipulate arrays and transform them into a new one.

The flat() method is used to flatten a multi-dimensional array into a single-dimensional array. This method takes an optional argument, which determines the depth of flattening. By default, it flattens the array only one level deep. For example:

Code For flat Method In JavaScript

const multiDimensionalArray = [1, [2, 3], [[4, 5]]];
const singleDimensionalArray = multiDimensionalArray.flat();
console.log(singleDimensionalArray);

Output

[1, 2, 3, [4, 5]]

The flatMap() method is a combination of the map() and flat() methods. It maps each element to a new array, then flattens the resulting arrays into a single array.

The flatMap() method takes a callback function as its argument, which is called for each element in the original array. This callback function should return an array, which is then flattened. For example:

Code For flatMap Method In JavaScript

const array = [1, 2, 3, 4];
const mappedArray = array.flatMap(x => [x, x * 2]);
console.log(mappedArray);

Output

[1, 2, 2, 4, 3, 6, 4, 8]

Both flat() and flatMap() were added in ECMAScript 2019, and are supported in modern browsers and Node.js.

Conclusion

If you liked this post Flat And flatMap In JavaScript, then please share this with your friends and make sure to bookmark this website for more awesome content.


If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Share on:

NK Coderz is a Computer Science Portal. Here We’re Proving DSA, Free Courses, Leetcode Solutions, Programming Languages, Latest Tech Updates, Blog Posting Etc.

Leave a Comment