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

A function that joins two arrays JS

I need to write a function combineArray(arr1, arr2), which takes 2 arrays, and returns a new array consisting only of numeric elements of arrays arr1 and arr2.
For example:

 combineArray([12, "User01", 22, true, -8], ["Index", 6, null, 15]));  result --> [12, 22, -8, 6, 15]

I tried to do it like this:

function combineArray(arr1, arr2) {
    let numArr = [];
    let newArr = arr1.concat(arr2);
    for(let i = 0; i < newArr.lenght; i++){
        if(typeof newArr[i] == "number") numArr.push(newArr[i]);
    }
    return numArr
}

let result = combineArray([12, "User01", 22, true, -8], ["Index", 6, null, 15])
console.log(result)

But my function returns empty array.

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

>Solution :

You can do it like this:

function returnNums(arr1, arr2) {
  let numArr = []
  for (const val of arr1) {
    if (typeof val === 'number') numArr.push(val)
  }
  for (const val of arr2) {
    if (typeof val === 'number') numArr.push(val)
  }
  return numArr;
}

console.log(returnNums([1, 2, 'a'], [3, 4, 'b']))

Also, the reason your code didn’t work is because there is a typo. It’s length, not lenght.

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