Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kbariotis
Last active December 12, 2016 10:34
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 kbariotis/9fba1983e872c2081100f5754740a915 to your computer and use it in GitHub Desktop.
Save kbariotis/9fba1983e872c2081100f5754740a915 to your computer and use it in GitHub Desktop.
Flatten nested array using reduce
/**
* 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), []);
}
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