Created
August 25, 2016 01:11
-
-
Save tortillaj/05d1db83b6202436e63c76b764d05917 to your computer and use it in GitHub Desktop.
Flatten multi-dimensional arrays in JavaScript
This file contains hidden or 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
(function() { | |
if (!Array.prototype.flatten) { | |
Array.prototype.flatten = function(array) { | |
'use strict'; | |
// check if called on null object | |
if (this == null) { | |
throw new TypeError('Array.prototype.flatten must not be called on a null or undefined object.'); | |
} | |
// check if argument is an Array | |
if (!array instanceof Array) { | |
throw new TypeError(array + ' is not an Array.'); | |
} | |
// check if argument is empty | |
if (!array.length) { | |
throw new RangeError('Cannot flatten empty Array.'); | |
} | |
var result = array; | |
// reduce array by concatenation, funnel any | |
// sub-Arrays into this function to handle recursively | |
result = array.reduce(function(start, next) { | |
return start.concat(Array.isArray(next) ? Array.prototype.flatten(next) : next); | |
}, []); | |
return result; | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use as
Array.prototype.flatten(arrayToFlatten)
. For example: