Skip to content

Instantly share code, notes, and snippets.

@tortillaj
Created August 25, 2016 01:11
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 tortillaj/05d1db83b6202436e63c76b764d05917 to your computer and use it in GitHub Desktop.
Save tortillaj/05d1db83b6202436e63c76b764d05917 to your computer and use it in GitHub Desktop.
Flatten multi-dimensional arrays in JavaScript
(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;
}
}
})();
@tortillaj
Copy link
Author

tortillaj commented Aug 25, 2016

Use as Array.prototype.flatten(arrayToFlatten). For example:

var arr = [1, 2, [4, 5], 2, 3, [4, 5, [6]]];
Array.prototype.flatten(arr);
// [1, 2, 4, 5, 2, 3, 4, 5, 6]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment