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.
>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.