Skip to content

Instantly share code, notes, and snippets.

@skamenetskiy
Created July 31, 2015 11:50
Show Gist options
  • Save skamenetskiy/696c35f67e4287988fff to your computer and use it in GitHub Desktop.
Save skamenetskiy/696c35f67e4287988fff to your computer and use it in GitHub Desktop.
#!/usr/local/bin/node
/**
* Converts current array to flat array
* @returns {Array}
*/
Array.prototype.flatten = function () {
/**
* The result container
* @type {Array}
*/
var result = [];
// Go through array items recursively and flatten them
this.forEach(function (item) {
if (item instanceof Array) {
return item
.flatten()
.forEach(function (item) {
result.push(item)
})
}
result.push(item)
});
return result
};
/**
* The provided example
* @type {Number[]}
*/
var exampleArray = [[1, 2, [3]], 4];
console.log(exampleArray.flatten());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment