Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging many arrays from Promise.all

When Promise.all completes it returns an array of arrays that contain data. In my case the arrays are just numbers:

[
    [ 1, 4, 9, 9 ],
    [ 4, 4, 9, 1 ],
    [ 6, 6, 9, 1 ]
]

The array can be any size.

Currently I'm doing this:

let nums = []
data.map(function(_nums) {
    _nums.map(function(num) {
        nums.push(num)
    })
})

Is there an alternative way of doing this? Does lodash have any functions that are able to do this?

like image 311
BugHunterUK Avatar asked Aug 19 '16 23:08

BugHunterUK


2 Answers

ES2019 introduced Array.prototype.flat which significantly simplifies this to:

const nums = data.flat();

const data = [
  [ 1, 4, 9, 9 ],
  [ 4, 4, 9, 1 ],
  [ 6, 6, 9, 1 ]
];

const nums = data.flat();

console.log(nums);

Original Answer

Use reduce and concat:

data.reduce(function (arr, row) {
  return arr.concat(row);
}, []);

Or alternatively, concat and apply:

Array.prototype.concat.apply([], data);
like image 149
zzzzBov Avatar answered Sep 19 '22 07:09

zzzzBov


I would do as follows;

var a = [
    [ 1, 4, 9, 9 ],
    [ 4, 4, 9, 1 ],
    [ 6, 6, 9, 1 ]
],
    b = [].concat(...a)

console.log(b)
like image 29
Redu Avatar answered Sep 20 '22 07:09

Redu