Why array dont concat with other array(by assignment, I can't use Array.flat method)

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

>Solution :

Array.concat returns a new array. You will either need to reassign the array (bad) or use something like the spread operator.

newarr.push(...arr[i])

Edit

I like @mplingjan comment. Array.flat could be a good choice here.

const flat = function (arr, n) {
    if (n == 0) {
        return arr;
    } else if (n == 1) {
        let newarr = []
        for (let i = 0; i < arr.length; i++) {
            newarr.push(...Array.of(arr[i]).flat())             
        }
        return newarr
    }
};

Leave a Reply