I have
const flat = function(arr, n) {
if (n == 0) {
return arr;
} else if (n == 1) {
let newarr = []
for (let i = 0; i < arr.length; i++) {
if (Number.isInteger(arr[i])) {
newarr.push(arr[i])
} else if (Array.isArray(arr[i])) {
newarr.concat(arr[i]) //look here
}
}
return newarr
}
};
console.log(flat([2,4,[2,4,9],1,6],1))
that is, if I call a function with values
([2,4,[2,4,9],1,6],1)
I should get the answer
2,4,2,4,9,1,6
but I get
2,4,1,6
that is, without an array inside the array
2
Answers
Array.concat returns a new array. You will either need to reassign the array (bad) or use something like the spread operator.
Edit
I like @mplingjan comment. Array.flat could be a good choice here.
You could also do it recursively.
newarr.push(…flat(arr[i]))