Flatten an Array One Level Deep in Javascript
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