Flattening multidimensional arrays in javascript -
i need flatten multidimensional arrays code flattens 1 array , stops. wrong? how transfer elements no arrays.
function flatten(arr) { // i'm steamroller, baby arr.reduce(function (flat, toflatten) { return flat.concat(array.isarray(toflatten) ? flatten(toflatten) : toflatten); },[]); } flatten([[['a']], [['b']]]); assert.deepequal(flatten([[['a']], [['b']]]), ['a', 'b'], 'should flatten nested arrays'); should flatten nested arrays: expected [ [ 'a' ], [ 'b' ] ] equal [ 'a', 'b' ]
you're doing right -- missing return
statement.
function flatten(arr) { // i'm steamroller, baby return arr.reduce(function (flat, toflatten) { return flat.concat(array.isarray(toflatten) ? flatten(toflatten) : toflatten); }, []); } console.log(flatten([[['a']], [['b']]]));
Comments
Post a Comment