Skip to content

Instantly share code, notes, and snippets.

@rbj325
Last active April 24, 2019 16:04
Show Gist options
  • Select an option

  • Save rbj325/f2262f7c0f3f7d58abcfcf4a20d58bc3 to your computer and use it in GitHub Desktop.

Select an option

Save rbj325/f2262f7c0f3f7d58abcfcf4a20d58bc3 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]

flatten

Flatten an array of arbitrarily nested arrays of integers into a flat array of integers.

Usage

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

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

Test

Launch

node flatten.test.js

License

MIT

/**
* flatten
* @function
*
* 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]
*
* example usage:
*
* flatten([[1,2,[3]],4]) // [1, 2, 3 , 4]
*
* @param {Array} input
* @returns {Array} output
*
* License: MIT
* Author: Rob Jones
*/
function flatten (input) {
// If the input is an array, flatten it with a recursive reducer.
if (Array.isArray(input)) {
return input.reduce(
function flattener (result, value) {
if (Array.isArray(value)) {
// If value is an array, flatten it recursively
return result.concat(value.reduce(flattener, []))
} else {
// If it's not an array append it to the result
return result.concat(value)
}
}
, []
)
} else {
throw new TypeError('Argument must be an array')
}
}
// CommonJS / ES6 export
module.exports = exports.default = flatten
// To run this test, launch
//
// node flatten.test.js
const assert = require('assert')
const flatten = require('./flatten')
const tests = [
{
input: [[1,2,[3]],4],
output: [1, 2, 3, 4]
},
{
input: [],
output: []
},
{
input: [1, [2, [3, [4, 5, [6, 7]], 8]]],
output: [1, 2, 3, 4, 5, 6, 7, 8,]
}
]
tests.forEach(({ input, output }) => {
assert.deepEqual(flatten(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