How to Implement Array Flat and FlatMap Methods in JavaScript

Learn how to use the Array flat and flatMap methods in JavaScript and speed up your development process. Our guide covers implementation details, examples, and more.

#javascript
#nodejs
#methods
#array
How to Implement Array Flat and FlatMap Methods in JavaScript
Picture by T Design

As a programming language, JavaScript is constantly evolving, adding new syntax, features, or abstractions which help developers to easily solve complex problems.

With ES10, we received a couple of new methods for arrays to work on a common operation you’ve probably seen many times in your code: spreading arrays’ elements into a new one.

These two methods are flat and flatMap. Let’s talk about what they do and a possible polyfill to simulate their behaviors in old browsers.

flat

The flat method, part of the array prototype, returns a new array, spreading the content of nested arrays found in the list. It eventually takes an optional depth argument that represents how many nested levels of our array we want to spread before stopping.

As this method is not fully supported by all the browsers (check the supported list here: Caniuse), let's implement an imperative and performing solution to achieve the same result:

js
const arr = [1, 2, 3, [1, 2, 3, 4, [2, [3, 4]]]];

function flat(array, depth = 1) {
const flattend = [];

for (const el of array) {
if (Array.isArray(el) && depth) {
flattend.push(...flat(el, depth - 1));
} else {
flattend.push(el);
}
}

return flattend;
}

console.log(flat(arr)); // [ 1, 2, 3, 1, 2, 3, 4, [ 2, [ 3, 4 ] ] ]
console.log(flat(arr, 2)); // [ 1, 2, 3, 1, 2, 3, 4, 2, [ 3, 4 ] ]
console.log(flat(arr, 3)); // [ 1, 2, 3, 1, 2, 3, 4, 2, 3, 4 ]
console.log(flat(arr, Infinity)); // [ 1, 2, 3, 1, 2, 3, 4, 2, 3, 4 ]

flatMap

The flatMap method works very similarly to flat, but it iterates over every element and flats the result of the passed callback function into a new array. We could see it as a combination of the usual map and flat methods.

The difference from flat is that this method only flattens the callback result by one level, and not deeply as flat does.

js
const users = [
{ name: 'Marco', colors: ['blue', 'green'] },
{ name: 'Leone', colors: ['red'] },
{ name: 'Berta', colors: ['yellow', 'white'] }
];

function flatMap(array, callback) {
const flattend = [];

for (let i = 0; i < array.length; i++) {
const elementArr = callback(array[i], i, array);
flattend.push(...elementArr);
}

return flattend;
}

const allColors = flatMap(users, user => user.colors);
allColors; // [ 'blue', 'green', 'red', 'yellow', 'white' ]

Last updated: