Last active
October 30, 2017 20:00
-
-
Save carlospliego/dbe6412f15970ffd1cc331e79119e73b to your computer and use it in GitHub Desktop.
Flatten n-depth array es6
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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