Flat nested array in JavaScript

Convert
[[0, 1], [2, 3], [4, 5]]
to
[0, 1, 2, 3, 4, 5]
or
[4, 5, 2, 3, 0, 1]

Solution 1:

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
  return a.concat(b);
});
// [0, 1, 2, 3, 4, 5]
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
  return b.concat(a);
});
// [4, 5, 2, 3, 0, 1]

See Array.prototype.reduce() for more examples.

Solution 2:

var flattened = [].concat.apply([], [[0, 1], [2, 3], [4, 5]]);
// [0, 1, 2, 3, 4, 5]
var flattened = [].concat.apply([], [[0, 1], [2, 3], [4, 5]].reverse());
// [4, 5, 2, 3, 0, 1]

See Array.prototype.concat() for more examples.

Yang Zhao

Read more posts by this author.


Comment