Created
January 18, 2020 05:31
-
-
Save gkucmierz/e9b681058ade9ee5c3236e6f51ffc272 to your computer and use it in GitHub Desktop.
iterate over nested arrays similar to native map
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
| // similar to map, but works with nested arrays | |
| const deepMap = (arr, fn, idxs = [], startLen = 0) => { | |
| const res = []; | |
| for (let i = 0; i < arr.length; ++i) { | |
| const len = startLen + res.length; | |
| if (Array.isArray(arr[i])) { | |
| res.push(...deepMap(arr[i], fn, [...idxs, i], len)); | |
| } else { | |
| res.push(fn(arr[i], idxs, len)); | |
| } | |
| } | |
| return res; | |
| }; | |
| // example use | |
| function arrayDepth(arr) { | |
| return Math.max(0, ...deepMap(arr, (el, idxs) => idxs.length)) + 1; | |
| } | |
| console.log(arrayDepth([1, [2, [3, [4, [5, [6], 5], 4], 3], 2], 1]), 6); | |
| console.log(arrayDepth([true]), 1); | |
| console.log(arrayDepth([]), 1); | |
| console.log(arrayDepth([2, 'yes', [true, false]]), 2); | |
| console.log(arrayDepth([2.0, [2, 0], 3.7, [3, 7], 6.7, [6, 7]]), 2); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment