Skip to content

Instantly share code, notes, and snippets.

@compwright
Created August 23, 2016 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save compwright/32f505e81a60af46578e9fcd8ab39a47 to your computer and use it in GitHub Desktop.
Save compwright/32f505e81a60af46578e9fcd8ab39a47 to your computer and use it in GitHub Desktop.
Flattens an array of arbitrarily nested arrays of integers into a flat array of integers
'use strict';
Array.prototype.flatten = function() {
var flattened = [];
this.map(function(element) {
if (Array.isArray(element)) {
// If the array element is an array,
// flatten it, then push each element
// onto the master flattened array.
element.flatten().map(function(e) {
flattened.push(e);
});
} else {
flattened.push(element);
}
});
return flattened;
};
var input = [[1,2,[3]],4],
expected = [1,2,3,4],
actual = input.flatten();
// Array comparison in Javascript does not behave as expected
// since arrays are really objects
if (!(actual < expected || actual > expected)) {
console.log('PASS', actual);
} else {
console.log('FAIL, expected', expected, 'but got', actual);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment