Created
June 28, 2019 21:03
-
-
Save madroneropaulo/af156a69308b6948b7e92392afa65595 to your computer and use it in GitHub Desktop.
Array Flattener
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
function flattenArray(nestedArray) { | |
const flatArr = []; | |
function flattenerFunc (arr) { | |
arr.forEach(el => { | |
if (Array.isArray(el)) { | |
flattenerFunc(el); | |
} else { | |
flatArr.push(el); | |
} | |
}); | |
} | |
flattenerFunc(nestedArray); | |
return flatArr | |
} | |
module.exports = flattenArray; |
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 flattenArray = require("./flattener"); | |
test('flattens integer array', () => { | |
const nestedArr = [0,[1,2,3,[4,[5]]],6,7]; | |
const flatteredArr = flattenArray(nestedArr); | |
expect(flatteredArr).toEqual([0,1,2,3,4,5,6,7]); | |
}); | |
test('flattens any array', () => { | |
const anyNestedArr = ['a', [0, undefined], {name: "hello"}, [false, 5, {hello: "world"}]]; | |
const flatteredArr = flattenArray(anyNestedArr); | |
expect(flatteredArr).toEqual(['a', 0, undefined, {name: "hello"}, false, 5, {hello: "world"}]); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requires jest. Works not only with numbers, but with any type.