JavaScript flattening an array of arrays of objects JavaScript flattening an array of arrays of objects arrays arrays

JavaScript flattening an array of arrays of objects


You can use Array.concat like bellow:-

var arr = [['object1', 'object2'],['object1'],['object1','object2','object3']];var flattened = [].concat.apply([],arr);

flattened will be your expected array.

ES 2020 gives the flat, also flatMap if you want to iterate over, to flat lists of lists:

[['object1'], ['object2']].flat() // ['object1', 'object2']


A recursive solution for deep (nested) flattening:

function flatten(a) {  return Array.isArray(a) ? [].concat.apply([], a.map(flatten)) : a;}

A bit more compactly with ES6:

var flatten = a => Array.isArray(a) ? [].concat(...a.map(flatten)) : a;

For fun, using a generator named F for "flatten", to lazily generate flattened values:

function *F(a) {  if (Array.isArray(a)) for (var e of a) yield *F(e); else yield a;}>> console.log(Array.from(F([1, [2], 3])));<< [ 1, 2, 3 ]

For those not familiar with generators the yield * syntax yields values from another generator. Array.from takes an iterator (such as results from invoking the generator function) and turns it into an array.


If you only need simple flatten, this may works:

var arr = [['object1', 'object2'],['object1'],['object1','object2','object3']];var flatenned = arr.reduce(function(a,b){ return a.concat(b) }, []);

For more complex flattening, Lodash has the flatten function, which maybe what you need: https://lodash.com/docs#flatten

//Syntax: _.flatten(array, [isDeep])_.flatten([1, [2, 3, [4]]]);// → [1, 2, 3, [4]];// using `isDeep` to recursive flatten_.flatten([1, [2, 3, [4]]], true);// → [1, 2, 3, 4];