Skip to content

Instantly share code, notes, and snippets.

@gkucmierz
Created January 18, 2020 05:31
Show Gist options
  • Save gkucmierz/e9b681058ade9ee5c3236e6f51ffc272 to your computer and use it in GitHub Desktop.
Save gkucmierz/e9b681058ade9ee5c3236e6f51ffc272 to your computer and use it in GitHub Desktop.
iterate over nested arrays similar to native map
// 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