skip to Main Content

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


  1. 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
        }
    };
    
    Login or Signup to reply.
  2. You could also do it recursively.

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search