Skip to content

Instantly share code, notes, and snippets.

@astopo
Created July 2, 2019 14:08
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 astopo/f76d32e4aab61fff477f6dc9736aeddf to your computer and use it in GitHub Desktop.
Save astopo/f76d32e4aab61fff477f6dc9736aeddf to your computer and use it in GitHub Desktop.
Flatten an array of arbitrarily nested arrays of integers into a flat array of integers.

Conversio Code Test

Github repo here

module.exports = flattenArray
/**
* Flatten a multi-dimensional array.
*
* @param {Number[]} array
*/
function flattenArray(array) {
return array.reduce((result, el) => {
// If the element is an array, continue to flatten it.
if (Array.isArray(el)) {
return result.concat(flattenArray(el))
}
// Do not accept non integer elements
if (!Number.isInteger(el)) {
return result
}
// Otherwise, we now have the element, push it into the result.
result.push(el)
return result
}, [])
}
// Spec file for flatten array method.
const flattenArray = require('../index')
describe('flattenArray method', () => {
it('should flatten an abritrary array of nested arrays', () => {
const array = [1, [2, 3], 4, [5, [6]]]
const flatArray = flattenArray(array)
const expectedArray = [1, 2, 3, 4, 5, 6]
expect(flatArray).toEqual(expectedArray)
})
it('should return only an array of integers', () => {
const array = [1, [2, 3], 4.05, ['5', [6]]]
const flatArray = flattenArray(array)
const expectedArray = [1, 2, 3, 6]
expect(flatArray).toEqual(expectedArray)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment