0

An array shows 3 numbers randomly, and I had to write a code that sums the 3 numbers, but the array has a trick to sometimes show a string:

[96, ".!asd", 182]
["@#$%", 5, 43]
[64, "bd", 48]

I would like to use an "if" that would return "not valid" if there's a string in the array.

if (...){
    return not valid
}

Please, if there's a way to identify any string, could you tell me the code?

7 Answers7

2

You can use Array.prototype.some() to see if your array contains NaN's

var x = [96, ".!asd", 182]
var y = [96, 1000, 182]
console.log(x.some(isNaN))
console.log(y.some(isNaN))
user3483203
  • 50,081
  • 9
  • 65
  • 94
1

You can use isNaN to determine if a stirng is a number

isNaN('123') //false   
isNaN('Hello') //true    
Striped
  • 2,544
  • 3
  • 25
  • 31
Ariel Haim
  • 86
  • 7
1

Use the object Number:

if (Number.isNaN(+element_in_array)) return "Not Valid!!"

function sum(array) {
  if (array.some((n) => Number.isNaN(+n))) {
    return "Invalid data, at least one element is not a number.";
  }
  
  return array.reduce((a, n) => a + Number(n), 0);
}

console.log(sum([96, ".!asd", 182]))
console.log(sum(["@#$%", 5, 43]))
console.log(sum([64, "bd", 48]))
console.log(sum([64, 44, 48]))
Ele
  • 33,468
  • 7
  • 37
  • 75
1

You should use the isNaN function as it is explained here : Is there a (built-in) way in JavaScript to check if a string is a valid number?

isNaN(123)         // false
isNaN('123')       // false
isNaN('1e10000')   // false (This translates to Infinity, which is a number)
isNaN('foo')       // true
isNaN('10px')      // true
0

You could use NaN to determine if all elements are numbers by using an unary plus to convert the string to number. If succeed, you get a number for summing, if not then NaN is returned and summed. A single NaN spoils the result and the result is NaN.

function not(fn) {
    return function (v) {
        return !fn(v);
    };
}

function sum(array) {
    return array.reduce((a, b) => +a + +b);
}

console.log([[96, ".!asd", 182], ["@#$%", 5, 43], [64, "bd", 48], [2, 3, 5]].map(sum).filter(not(isNaN)));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
-1

try using typeof to validate wether or not you are dealing with a string.mdn typeof

jhn_bdrx
  • 36
  • 3
-2

You can use if type(x) == str to check if a variable x is of type String. It is a built-in function. Please refer to official python documentation to know more.

https://docs.python.org/3/library/functions.html#type

Shashi
  • 1