rsk82 rsk82 - 3 months ago 10
Javascript Question

Is there an easy way to make nested array flat?

That is to make this:

[ ['dog','cat', ['chicken', 'bear'] ],['mouse','horse'] ]


into:

['dog','cat','chicken','bear','mouse','horse']

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

It's note worthy that reduce isn't supported in IE 8 and lower.

developer.mozilla.org reference

Comments