Photo by Tabea Schimpf on Unsplash

Member-only story

JavaScript flat() vs flatMap()

Techmade
3 min readJan 25, 2024

--

In JavaScript, arrays are one of the most commonly used data structures. They can become complex, especially when dealing with nested arrays. Two array methods that are particularly useful for handling nested arrays are flat() and flatMap(). These methods, introduced in ES2019, offer elegant solutions for flattening arrays and mapping over arrays, then flattening the result. This article will delve into the details, differences, and practical applications of flat() and flatMap(), along with illustrative code examples.

The flat() Method

What is flat()?

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to a specified depth.

var newArray = arr.flat([depth]);
  • arr: The array to flatten.
  • depth (optional): The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.

Example 1: Basic Usage

let nestedArray = [1, [2, 3], [4, [5, 6]]];
let flattenedArray = nestedArray.flat();

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

Example 2: Specifying Depth

let nestedArray = [1, [2, [3, [4, 5]]]];
let flattenedArray = nestedArray.flat(2);

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

The flatMap() Method

What is flatMap()?

The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map followed by a call to flat of depth 1.

var newArray = arr.flatMap(function callback(currentValue[, index[, array]]) {
// return element for newArray, after executing something
}[, thisArg]);
  • callback: Function that produces an element of the new Array, taking three arguments:
  • currentValue: The current element being processed in the array.
  • index (optional): The index of the current element being processed in the array.
  • array (optional): The array flatMap was called upon.

--

--

Techmade
Techmade

Written by Techmade

Learn how to land a job in tech and grow to a senior software engineer in big tech or startups.

No responses yet