Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flatten an array without using .flat();

Tags:

javascript

how can i flatten an array without using flat(). by 1 level?

so far i have this

function flatten(array) {
  let flattened = [];
  for (let i = 0; i < array.length; i++) {
    const current = array[i];
    for (let j = 0; i < current.length; j++) {
      flattened.push(current[j])
    }
  }
  return flattened
}

console.log(flatten([['foo', 'bar'], ['baz', 'qux']]));
// -> ["foo", "bar", "baz", "qux"]
flatten([[1], [2], 3, 4, [5]]);
// -> [1, 2, 3, 4, 5]
flatten([false, [true, [false]], [true]]);
// -> [false, true, [false], true]
flatten([]);
// -> []

and its crashing my memory

like image 528
tryingToBeBetter Avatar asked Dec 13 '22 08:12

tryingToBeBetter


1 Answers

I hope this helps

var twoDimension = [[1], [2], 3, 4, [5]];

var plano = twoDimension.reduce((acc, el) => acc.concat(el), []);

console.log(plano);
like image 167
sonEtLumiere Avatar answered Dec 21 '22 01:12

sonEtLumiere