Skip to content

Instantly share code, notes, and snippets.

@AraujoJordan
Created December 15, 2018 20:53
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 AraujoJordan/a232014e8bbeb8376377b08dbbc22fb6 to your computer and use it in GitHub Desktop.
Save AraujoJordan/a232014e8bbeb8376377b08dbbc22fb6 to your computer and use it in GitHub Desktop.
Convert a nested number array into an one-dimensional array.
#!/usr/bin/env node
/**
* Simple conversor from a nested number array into an one-dimensional array.
* Made for citrusbyte code test
* Jordan L. Araujo Jr. - jordanjr.92@gmail.com
* 15/12/2018
*/
//run test cases
testCases();
/**
* Recursively enter in a nested array and put
* the numbers inside an one-dimensional array
* @param nestedArray nested Array that you want to fix
* @param resultArr the result numbers of the nested array into an one-dimensional array
* @returns an one-dimensional array with all the numbers of the nested array in order
*/
function recursivelyNestedArrayFix(nestedArray, resultArr) {
if (nestedArray.length !== 0) {
for (let arrElement of nestedArray) {
if (typeof arrElement === 'number') {
resultArr.push(arrElement)
} else {
recursivelyNestedArrayFix(arrElement, resultArr);
}
}
}
return resultArr
}
/**
* Run 10 test cases with some possible break values
*/
function testCases() {
let test1 = [[1, 2, [3]], 4];
let test2 = [[1, 2, [3, 4, 5]], 6];
let test3 = [[[1], 2, [3]], 4, [5, [6]]];
let test4 = [];
let test5 = [[[[[[[[[[[[[[[1]]]], 2]]]]], 3]]]]], 4];
let test6 = [1, [2], 3, [4], 5];
let test7 = [[1], [2], [3], [4]];
let test8 = [[1, 2, [3]], 4];
let test9 = [1, 2, 3, 4];
let test10 = [[[[[[[[[[[[[[[[[[[[[1]]]]]]]]]]]]]]]]]]]]];
console.log(JSON.stringify(test1) + '->' + JSON.stringify(recursivelyNestedArrayFix(test1, [])));
console.log(JSON.stringify(test2) + '->' + JSON.stringify(recursivelyNestedArrayFix(test2, [])));
console.log(JSON.stringify(test3) + '->' + JSON.stringify(recursivelyNestedArrayFix(test3, [])));
console.log(JSON.stringify(test4) + '->' + JSON.stringify(recursivelyNestedArrayFix(test4, [])));
console.log(JSON.stringify(test5) + '->' + JSON.stringify(recursivelyNestedArrayFix(test5, [])));
console.log(JSON.stringify(test6) + '->' + JSON.stringify(recursivelyNestedArrayFix(test6, [])));
console.log(JSON.stringify(test7) + '->' + JSON.stringify(recursivelyNestedArrayFix(test7, [])));
console.log(JSON.stringify(test8) + '->' + JSON.stringify(recursivelyNestedArrayFix(test8, [])));
console.log(JSON.stringify(test9) + '->' + JSON.stringify(recursivelyNestedArrayFix(test9, [])));
console.log(JSON.stringify(test10) + '->' + JSON.stringify(recursivelyNestedArrayFix(test10, [])));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment