0

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?

2

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

should I delete my answer? I can't leave comments yet
Well, that's a correct answer, and you cite the source, so you're fine. Oh, and you can now comment 🎉

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.