Lucio Flores
2018-09-05T17:22:30Z

flatArray.js

| //Lucio Flores.
|
| //recursive function that receive a object and if it's a number then it's added to the output array, it's is an array then call itself.
| let flatIt = function(arrayIn, arrayOut){
| if(typeof(arrayIn) == "number"){
| arrayOut.push(arrayIn)
| return
| }
| else{
| arrayIn.forEach(function(item,index){
| flatIt(item, arrayOut)
| })
| }
| }
|
| //variables
| let input = "[[1, 2,[3]],4,5,[[[6]]],[7,8,9],10, [11], 12]"
| let arrayOut = []
| let expected = [1,2,3,4,5,6,7,8,9,10,11,12]
| let arrayIn = JSON.parse(input) //parse array from string input
|
| //Execute function:
| flatIt(arrayIn, arrayOut)
|
| //Test
| if(expected.toString() == arrayOut.toString()){
| console.log("Test passed!")
| }
| else{
| console.log("Test failed!")
| }
|
| console.log("input: " + input )
| console.log("expected: " + expected.toString())
| console.log("output: " + arrayOut.toString())
|
| //Update 05/09/2018
| //React implementation: https://llkx7kvy2q.codesandbox.io/
| //Code: https://github.com/Lvcios/FlatteningIntegerArray/tree/master/