0

so i have an array, containing arrays inside:

var arr = [
    [1,2,3,4,5],
    [6,7],
    [8,9,0]
];

What's the most elegant way to extract

[1,2,3,4,5,6,7,8,9,0]

I can make it like:

var final = [];
params.forEach(function(bulk){
    final = final.concat(bulk);
});

but was looking for something more elegant / pretty

André Alçada Padez
  • 9,331
  • 19
  • 58
  • 109
  • This is a duplicate of so, so many questions. – Etheryte Jan 18 '15 at 19:55
  • possible duplicate of [Merge/flatten an Array of Arrays in JavaScript?](http://stackoverflow.com/questions/10865025/merge-flatten-an-array-of-arrays-in-javascript) – Etheryte Jan 18 '15 at 19:55

2 Answers2

1

How about:

Array.prototype.concat.apply([], [
    [1,2,3,4,5],
    [6,7],
    [8,9,0]
]);

// [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

Note that you can further reduce it to [].concat.apply but might have a cost of creation of an extra (empty) array (I guess this is browser implementation-dependent).

Oleg
  • 8,818
  • 2
  • 40
  • 55
1

Try this

console.log([].concat.apply([], arr));

If array has only numbers you also can use this

arr.toString().split(',').map(Number);

Example

Oleksandr T.
  • 69,412
  • 16
  • 152
  • 136