Skip to content

Instantly share code, notes, and snippets.

@wilmoore
Last active March 12, 2019 16:09
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 wilmoore/579383ea7288b842f522d04c06232007 to your computer and use it in GitHub Desktop.
Save wilmoore/579383ea7288b842f522d04c06232007 to your computer and use it in GitHub Desktop.
Flattens a nested array recursively (A quick ES6 prototype of my https://www.npmjs.com/package/flatten-arr)
const toString = Object.prototype.toString
/**
* Recursive list item concatenation.
*
* @param {Array} nested
* Nested array.
*
* @param {Array} flat
* Initial/Flattended array.
*
* @return {Array}
* Flattened array.
*/
const concat = (nested, flat) => {
let end = nested.length
let idx = -1
while (++idx < end) {
if (toString.call(nested[idx]) === '[object Array]') {
concat(nested[idx], flat)
} else {
flat.push(nested[idx])
}
}
return flat
}
/**
* Flattens a nested array recursively.
*
* @param {Array} list
* Nested array.
*
* @return {Array}
* Flattened array.
*/
exports.flatten = (list) => concat(list, [])
{
"name": "gist",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"test": "node test"
}
}
const assert = require('assert')
const { flatten } = require('./')
{
const original = [[1, 2, [3]], 4]
const expected = [1, 2, 3, 4]
assert.deepEqual(flatten(original), expected)
}
{
const original = [1, [[[2, [[3, 4]], 5], 6]], [7], [[[8]]], 9]
const expected = [1, 2, 3, 4, 5, 6, 7, 8, 9]
assert.deepEqual(flatten(original), expected)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment