Skip to content

Instantly share code, notes, and snippets.

@Integralist
Created May 20, 2015 08:35
Show Gist options
  • Save Integralist/749153aa53fea7168e7e to your computer and use it in GitHub Desktop.
Save Integralist/749153aa53fea7168e7e to your computer and use it in GitHub Desktop.
Array flatten function written in ES6 syntax
const flattenTco = ([first, ...rest], accumulator) =>
(first === undefined)
? accumulator
: (Array.isArray(first))
? flattenTco([...first, ...rest])
: flattenTco(rest, accumulator.concat(first))
const flatten = (n) => flattenTco(n, []);
console.log(flatten([[1,[2,[[3]]]],4,[5,[[[6]]]]]))
@yzrzya1
Copy link

yzrzya1 commented Jun 9, 2019

one hack solution. (deep nested also works)
JSON.stringify(arr).split(',').map(each => each.match(/[+-]?\d+(?:\.\d+)?/g)[0])

@coolskin2b
Copy link

one hack solution. (deep nested also works)
JSON.stringify(arr).split(',').map(each => each.match(/[+-]?\d+(?:\.\d+)?/g)[0])
work like a charm for number, but not with string ['un', 2, 'trois', 4, 'cinq'].

@DimitryDushkin
Copy link

For immutable solution, this should be the most performant one, because it uses only pop() and push():

const flatten = (list) => { 
  const stack = [list];
  const result = [];

  while(stack.length > 0) {
    const elem = stack.pop();
    if (Array.isArray(elem)) {
      for (let i = elem.length - 1; i >= 0; i--) {
        stack.push(elem[i]);
      }
    } else {
      result.push(elem);
    }
  }

  return result;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment