Created
August 23, 2016 15:01
-
-
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
This file contains 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
'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