Skip to content

Instantly share code, notes, and snippets.

@fibo
Last active December 3, 2020 13:59
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save fibo/0ec16d96b16719a045fd561cd74a12c8 to your computer and use it in GitHub Desktop.
Save fibo/0ec16d96b16719a045fd561cd74a12c8 to your computer and use it in GitHub Desktop.
Flatten an array of arbitrarily nested arrays of values into a flat array of values. e.g. [[1,2,[3]],4] -> [1,2,3,4].

flattenArray

Flatten an array of arbitrarily nested arrays of values into a flat array of values

Usage

// Both CommonJS and ES6 import syntaxes are supported
// import flattenArray from './flattenArray'
const flattenArray = require('./flattenArray')

flattenArray([[1,2,[3]],4]) // [1, 2, 3 , 4]

Test

Launch

node flattenArray.test.js

License

MIT

Latest sources here: https://gist.github.com/fibo/0ec16d96b16719a045fd561cd74a12c8

/**
* flattenArray
* @function
*
* Flatten an array of arbitrarily nested arrays of values into a flat array of values. e.g. [[1,2,[3]],4] -> [1,2,3,4].
*
* example usage:
*
* flattenArray([[1,2,[3]],4]) // [1, 2, 3 , 4]
*
* @param {Array} input
* @returns {Array} output
*
* License: MIT
* Author: Gianluca Casati a.k.a. fibo, http://g14n.info
* Sources here: https://gist.github.com/fibo/0ec16d96b16719a045fd561cd74a12c8
*/
function flattenArray (input) {
// Check that input is an array, if yes, flatten it with a recursive reducer.
if (Array.isArray(input)) {
return input.reduce(
function flattener (accumulator, value) {
if (Array.isArray(value)) {
// If array item is an array, flatten it recursively...
return accumulator.concat(value.reduce(flattener, []))
} else {
// ...otherwise append it to result array.
return accumulator.concat(value)
}
}
, []
)
} else {
throw new TypeError('Argument must be an array')
}
}
// CommonJS / ES6 export
module.exports = exports.default = flattenArray
// To run this test, launch
//
// node flattenArray.test.js
const assert = require('assert')
const flattenArray = require('./flattenArray')
const tests = [
{
input: [[1,2,[3]],4],
output: [1, 2, 3, 4]
},
{
input: [],
output: []
},
{
input: ['a', 'b'],
output: ['a', 'b']
},
{
input: [1, [2, [3, [4, 5, [6, 7], 8], 9], 10, 11], 12],
output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
}
]
tests.forEach(({ input, output }) => {
assert.deepEqual(flattenArray(input), output)
})
console.log(`run ${tests.length} tests`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment