Skip to content

Instantly share code, notes, and snippets.

@AquiGorka
Created March 15, 2016 18:18
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 AquiGorka/4ef41303e233b23b54ae to your computer and use it in GitHub Desktop.
Save AquiGorka/4ef41303e233b23b54ae to your computer and use it in GitHub Desktop.
Flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.split(search).join(replacement);
};
Array.prototype.flatten = function() {
return JSON.stringify(this).replaceAll('[','').replaceAll(']', '').split(',').map(item => parseInt(item));
};
var a = [[1,2,[3]],4];
console.log(a.flatten())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment