Skip to content

Instantly share code, notes, and snippets.

@tauil
Created September 26, 2017 15:43
Show Gist options
  • Save tauil/a910b0b9eb3c74d58b0e25635605fa11 to your computer and use it in GitHub Desktop.
Save tauil/a910b0b9eb3c74d58b0e25635605fa11 to your computer and use it in GitHub Desktop.
// [[1,2,[3]],4] -> [1,2,3,4]
function flatten(a) {
let result = [];
function searchItemAndAdd(array) {
array.forEach((item) => {
if (typeof(item) === 'object') {
searchItemAndAdd(item);
} else {
result.push(item);
}
});
}
searchItemAndAdd(a);
return result;
}
let sample = [1,2,3,[4,5],6, [7,8,[9]]];
console.log('Should contain 9 items: ', flatten(sample).length === 9);
console.log('Should not contain 6 items: ', flatten(sample).length !== 6);
console.log('Should not contain Array inside: ', (flatten(sample).filter((i) => typeof(i) === 'object').length === 0));
let sample2 = [1,[2,3]];
console.log('Should contain 9 items: ', flatten(sample2).length === 3);
console.log('Should not contain 6 items: ', flatten(sample2).length !== 2);
console.log('Should not contain Array inside: ', (flatten(sample2).filter((i) => typeof(i) === 'object').length === 0));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment