Flatten array of arrays with JavaScript

Today, We want to share with you javascript flatten array.In this post we will show you flatten(array javascript recursion, hear for It was always complicated to flatten an array in #JavaScript. we will give you demo and example for implement.In this post, we will learn about JavaScript Array Methods Tips, Tricks with an example.

How to Flatten a Nested Javascript Array?

You can use concat to merge arrays:

1: concat() and apply()

let flattened = [].concat.apply([], arr);
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]

2: spread operator in ES6

let flattened = [].concat(...arr);
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]

3: array.reduce()

let flattened = arr.reduce((acc, curVal) => {
return acc.concat(curVal)
}, []);
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]

Merge/flatten an array of arrays

var arrays = [
  ["$6"],
  ["$12"],
  ["$25"],
  ["$25"],
  ["$18"],
  ["$22"],
  ["$10"]
];
var merged = [].concat.apply([], arrays);

console.log(merged);

Huge arrays

flatten(Array(200000).fill([1]));

You can use those functions individually using those packages:

  • lodash.flatten
  • lodash.flattendeep
  • lodash.flattendepth

using lodash.flatten:

const flatten = require('lodash.flatten')

const websites = ['Online', ['Blog', 'Infinityknow']]

flatten(websites)
//['Online', 'Blog', 'Infinityknow']
['Online', ['Blog', 'Infinityknow']].flat()
//[ 'Online', 'Blog', 'Infinityknow' ]

using flat()

['Online', ['Blog', ['Infinityknow']]].flat()
//[ 'Online', 'Blog', [ 'Infinityknow' ] ]

['Online', ['Blog', ['Infinityknow']]].flat(2)
//[ 'Online', 'Blog', 'Infinityknow' ]

['Online', ['Blog', ['Infinityknow']]].flat(Infinity)
//[ 'Online', 'Blog', 'Infinityknow' ]

using flatMap()

['tiny Wife', 'is Great'].map(words => words.split(' '))
//[ [ 'tiny', 'Wife' ], [ 'is', 'Great' ] ]

['tiny Wife', 'is Great'].flatMap(words => words.split(' '))
//[ 'tiny', 'Wife', 'is', 'Great' ]

Deeper Nested Arrays

const twoLevelsDeep = [[1, [2, 2], 1]];

// depth = 1
twoLevelsDeep.flat();
// [1, [2, 2], 1]

// depth = 2
twoLevelsDeep.flat(2);
// [1, 2, 2, 1]

Array with Empty Slots

const missingNumbers = [1, , 3, , 5];

missingNumbers.flat();
// [1, 3, 5];

I hope you get an idea about javascript array.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment