Skip to content

Instantly share code, notes, and snippets.

@carlospliego
Last active October 30, 2017 20:00
Show Gist options
  • Save carlospliego/dbe6412f15970ffd1cc331e79119e73b to your computer and use it in GitHub Desktop.
Save carlospliego/dbe6412f15970ffd1cc331e79119e73b to your computer and use it in GitHub Desktop.
Flatten n-depth array es6
// Checks the equality of arrays based on value
const assertEqual = (arr1, arr2) => {
if (arr1.length !== arr2.length)
return false;
for (var i = arr1.length; i--;) {
if (arr1[i] !== arr2[i])
return false;
}
return true;
}
// Recursive algorithm to flatten n nested arrays
const flat = list => list.reduce(
(a, b) => a.concat(Array.isArray(b) ? flat(b) : b), []
);
// Tests
console.log(assertEqual(flat([1, 2, [23, 5, 2], [[6], [2, 3, 6]]]), [1, 2, 23, 5, 2, 6, 2, 3, 6]))
console.log(assertEqual(flat([[[[[1, 3, 4, [334, 5, 77, 91]]]]], 234]), [1, 3, 4, 334, 5, 77, 91, 234]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment