Last active
December 12, 2016 10:34
-
-
Save kbariotis/9fba1983e872c2081100f5754740a915 to your computer and use it in GitHub Desktop.
Flatten nested array using reduce
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
/** | |
* Takes a nested array and ftattens it | |
* | |
* @param {Array} val They input array | |
* @return {Array} val Flatten array | |
*/ | |
function flatten(val) { | |
/* | |
* Recursively walk over the array and concat all elements back to the first level array | |
* after making sure they are all integers | |
*/ | |
return val | |
.map(a => !Number.isInteger(a) && !Array.isArray(a) ? (() =>{throw new Error('Non integer element found')})() : a) | |
.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []); | |
} |
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
const assert = require('assert'); | |
// It should handle one level nested arrays | |
assert.deepEqual([1, 2, 3], flatten([1, [2, 3]])); | |
// It should handle two level nested arrays | |
assert.deepEqual([1, 2, 1, 2, 3], flatten([1, [2, [1, 2, 3]]])); | |
// Throws error when an element is not an integer | |
assert.throws(() => flatten([1, ['string', 2]]), /Non integer element found/, 'Non integer element found'); | |
// Throws error when an element is not an integer | |
assert.throws(() => flatten(['string', [1, 2, 3]]), /Non integer element found/, 'Non integer element found'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment