Skip to content

Instantly share code, notes, and snippets.

@ghmcadams
Created April 30, 2016 15:36
Show Gist options
  • Save ghmcadams/f896c5171b9bb2d9d3980812c5f7e41b to your computer and use it in GitHub Desktop.
Save ghmcadams/f896c5171b9bb2d9d3980812c5f7e41b to your computer and use it in GitHub Desktop.
Flatten an integer array in JavaScript
function flattenIntegerArray(array) {
var ret = [];
for (var i = 0; i < array.length; i++) {
if (Array.isArray(array[i])) {
//Add items from the sub array into the returned array
Array.prototype.push.apply(ret, flattenIntegerArray(array[i]));
} else if (Number.isInteger(array[i])) {
ret.push(array[i]);
} else {
// In JavaScript, you can't guarantee that the type
// is going to be consistent
throw new Error('Invalid type');
}
}
return ret;
}
var arr = [[1,2,[3]],4];
console.log(JSON.stringify(flattenIntegerArray(arr))); // [1,2,3,4]
var arr = [1, [3,5,2,[6,8,[4,[33,7,[9]]]]]];
console.log(JSON.stringify(flattenIntegerArray(arr))); // [1,3,5,2,6,8,4,33,7,9]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment