Skip to content

Instantly share code, notes, and snippets.

@wilmoore
Last active September 26, 2024 14:36
Show Gist options
  • 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)

Software Engineering :: Programming :: Languages :: JavaScript :: Example :: Flattens a nested array recursively

⪼ Made with 💜 by Polyglot.

Flattens a nested array recursively

A quick ES6 prototype of flatten-arr

Tests

tests are written without a test library, just intrinsice Node.js assert.

yarn test
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