Github repo here
Created
July 2, 2019 14:08
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}, []) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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