'How do you check for a type in an array?

I need to tell the program to search an array(that’s meant to be only numbers) if it contains any element that’s a string.

Also, the array is made up of the arguments to a function. Can someone please help? I’ve been trying to figure this out for at least an hour! This is what i did so far:

const sumAll = function(…args){
  const newArray = Array.from(args)
  for(let i = 0; i < newArray.length; i++){
    if(newArray[i] === NaN){
    return “ERROR”
    }
  }
}


Solution 1:[1]

let foundString = arrayWithPossiblyString.find(i=>isNaN(5-i));

Explanation:

  1. 5-"a" is a NaN.
  2. isNaN function can be used to chec if something is NaN

Solution 2:[2]

You can use arguments keyword to access all the variables which would be passed as arguments to that specific function. Further you can use isNaN function to determine weather the given argument is a number or not.

function check(){
    const arr = arguments
    for(const item of arr) {
        if(isNaN(item)){
            return "Error"
        }
    }
}

check(1, "Hello", "4")

Solution 3:[3]

I suggest using the isNaN function:

...
if(isNaN(newArray[i])) {
   return "ERROR";
}

Solution 4:[4]

You could check with Array#some and take isNaN as callback.

const sumAll = function(...args) {
    if (args.some(isNaN)) return "ERROR";
}

console.log(sumAll(1, 2, 3));     // undefined
console.log(sumAll(1, "two", 3)); // ERROR

Solution 5:[5]

const sampleErrorArr = ['zero', 1, 2, 3, 4,]
const sampleArr = [1, 2, 3, 4, 5]

function sumAll(arr) {
    let sum = 0
    let hasNumber = true
    arr.forEach((item, index) => {
        if (typeof item === 'number') {
            let temp = sum + item
            sum = temp
        }
        else {
            hasNumber = false
        }
    })

    return hasNumber == true ? sum : "Error"
}

console.log(sumAll(sampleErrorArr)) //Error
console.log(sumAll(sampleArr)) // 15

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anurag Vohra
Solution 2 Singh3y
Solution 3
Solution 4 Nina Scholz
Solution 5