MarketMan39
MarketMan39

Reputation: 208

JS: Most efficient way to flatten an array of unknown number of nested arrays?

Trying to see the most efficient way to flatten an array of n-nested arrays within it. I've just been using flat() for one-level nested arrays but is there a time-efficient helper function I can add to my app to universally flatten all arrays, regardless of n-number of nested arrays?

Upvotes: 0

Views: 611

Answers (1)

Pauline  Nemchak
Pauline Nemchak

Reputation: 480

You can use either recursive algorithm or use stack:

function flatDeep(arr, d = 1) {
   return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), [])
                : arr.slice();
};


function flatten(input) {
  const stack = [...input];
  const res = [];
  while(stack.length) {
    // pop value from stack
    const next = stack.pop();
    if(Array.isArray(next)) {
      // push back array items, won't modify the original input
      stack.push(...next);
    } else {
      res.push(next);
    }
  }
  // reverse to restore input order
  return res.reverse();
}

Using generator:

function* flatten(array, depth) {
    if(depth === undefined) {
      depth = 1;
    }
    for(const item of array) {
        if(Array.isArray(item) && depth > 0) {
          yield* flatten(item, depth - 1);
        } else {
          yield item;
        }
    }
}

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat

Upvotes: 4

Related Questions