In this article, we will see how to flatten an array using native javascript and also a glimpse of lodash(an open-source JavaScript utility library) _.flatten method.
During development, the developer needs to go through loops to prepare a single dimensional array out of a multi-dimensional array or flatten an array in JavaScript.
Array Flatten One Level Deep
Using reduce method
Now using reduce method
let nestedArray = [[12, [2, 4], 124, 7, 10, 8, [15, [6, 7]]]];
// Native
const flatten = nestedArray.reduce((a, b) => a.concat(b), []);
console.log(flatten);
// Output => [12, [2, 4], 124, 7, 10, 8, [15, [6, 7]]];
Using concat method
Now using concat method
let nestedArray = [[12, [2, 4], 124, 7, 10, 8, [15, [6, 7]]]];
const flatten = [].concat(...nestedArray);
console.log(flatten);
// Output => [12, [2, 4], 124, 7, 10, 8, [15, [6, 7]]]
Using flat method introduced in ES2019
Now using flat method introduced in ES2019
let nestedArray = [[12, [2, 4], 124, 7, 10, 8, [15, [6, 7]]]];
// Native(ES2019)
const flatten = nestedArray.flat();
console.log(flatten);
// Output => [12, [2, 4], 124, 7, 10, 8, [15, [6, 7]]]
Using flatMap method
Now using flatMap method
let nestedArray = [[12, [2, 4], 124, 7, 10, 8, [15, [6, 7]]]];
const flatten = nestedArray.flatMap((number) => number);
console.log(flatten);
// Output => [12, [2, 4], 124, 7, 10, 8, [15, [6, 7]]]
Array Flatten Using Lodash/Underscore library
Now using _.flatten method from Lodash/Underscore utility library.
let nestedArray = [[12, [2, 4], 124, 7, 10, 8, [15, [6, 7]]]];
// Underscore/Lodash
_.flatten(nestedArray);
console.log(flatten);
// Output => [12, [2, 4], 124, 7, 10, 8, [15, [6, 7]]]
Infinitely Nested Arrays using flat method introduced in ES2019
Suppose you want flatten an array infinitely deep. We just need to pass Infinity within flat method introduced in ES2019.
const infiniteDeep = [[12, [2, 4], 124, 7, 10, 8, [15, [6, 7]]]];
console.log(infiniteDeep.flat(Infinity));
// [12, 2, 4, 124, 7, 10, 8, 15, 6, 7]
This article is written in a ghostwriter.
Hope you like this!
Keep helping and happy ๐ coding
Related Articles
Deepen your understanding with these curated continuations.
Convert array to an object in JavaScript
This article explains simplest and quickest way to convert array to an object in JavaScript. Using widely accepted spread operator `...` makes easy to do it.
How to Update an Array Element in JavaScript
Learn the simplest ways to update array elements in JavaScript. This guide explains how to use assignment operators and modern methods to modify array values.
Identify whether device is a mobile or desktop
This article explains to flatten an array one level deep in javascript comparing with lodash _.flatten method.