BugHunterUK BugHunterUK - 3 months ago 8
Javascript Question

Merging many arrays

I've got 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?

Answer

You actually don't need any sort of library to do it, you can use concat with apply:

Promise.all(arrayOfPromises).then((arrayOfArrays) {
    return [].concat.apply([], arrayOfArrays);
});

If you are using lodash, though, you can use _.flatten(arrayOfArrays) for the same effect.

Comments