cresjoy cresjoy - 3 months ago 23
Javascript Question

Flatten n dimensional array without concat or reduce

here I flattened a two dimensional array like the following



function flatArray(a, b) {

return a.concat(b);

}

console.log([
['1', '2', '3'],
['4', '5', '6']
].reduce(flatArray));





Can i do this without reduce, and concat? I can't think of a way

Answer

Here is a relatively clean solution:

function flatten(ar) {
  // if ar is not an array, return it in a single-element array
  if(!Array.isArray(ar)) { return [ar]; }

  // convert each element of ar to a flattened copy of itself
  var flatEls = ar.map(flatten);

  // create a new array
  var newArr = [];

  // push the contents of each array in flatEls into the new array
  flatEls.forEach(function(el) { newArr.push.apply(newArr, el); });

  // return the new array
  return newArr;
}

console.log(flatten([['1', '2', '3'], ['4', '5', ['6'], ['7', '8']]]));

And without the comments:

function flatten(ar) {
  if(!Array.isArray(ar)) { return [ar]; }

  var flatEls = ar.map(flatten);

  var newArr = [];

  flatEls.forEach(function(el) { newArr.push.apply(newArr, el); });

  return newArr;
}

console.log(flatten([['1', '2', '3'], ['4', '5', ['6'], ['7', '8']]]));

Comments