Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
    }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading