Skip to content

Instantly share code, notes, and snippets.

@jacobroufa
Created June 24, 2017 02:09
Show Gist options
  • Select an option

  • Save jacobroufa/d90a7a3756ca863462caf6ea8d4a4e6a to your computer and use it in GitHub Desktop.

Select an option

Save jacobroufa/d90a7a3756ca863462caf6ea8d4a4e6a to your computer and use it in GitHub Desktop.
Flatten arbitrary nested array of integers.
var arrAllInts = [[1, 2, [3]], 4];
var arrWithOthers = [
() => {},
2,
[ 4, 'five' ],
[ Array.prototype, [
{},
6
]]
];
var oneFour = arrAllInts.reduce(flatten, []);
var twoSix = arrWithOthers.reduce(flatten, []);
console.log(arrAllInts, 'should reduce to [1, 2, 3, 4]', oneFour === [1, 2, 3, 4]);
console.log(arrWithOthers, 'should reduce to [2, 4, 6]', twoSix === [2, 4, 6]);
function flatten (prev, item) {
if (item && Number.isInteger(item)) {
prev.push(item);
}
if (item && Array.isArray(item)) {
prev = item.reduce(flatten, prev);
}
return prev;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment