Borislav Hadzhiev
Sat Oct 16 2021·2 min read
Photo by Motoki Tonn
To check if an array contains only numbers:
every()
method, passing it a function.number
.every
method returns true
, only if the condition is met for every
array element.const arr1 = [1, 2, 3]; const arr2 = [1, 2, 'three']; const arr3 = ['1', '2', '3']; function onlyNumbers(array) { return array.every(element => { return typeof element === 'number'; }); } console.log(onlyNumbers(arr1)); // 👉️ true console.log(onlyNumbers(arr2)); // 👉️ false console.log(onlyNumbers(arr3)); // 👉️ false
The function we pass to the Array.every method gets called with each element in the array, until it returns a falsy value or iterates over the entire array.
every
method short-circuits and returns false
.On each iteration we return whether the element has a type of number. The
condition has to be satisfied for all array elements for the every
method to
return true
.
If your array contains numbers that might be of type string
, use the
following approach instead.
const arr1 = [1, 2, 3]; const arr2 = [1, 2, 'three']; const arr3 = ['1', '2', '3']; function onlyNumbers(array) { return array.every(element => { return !isNaN(element); }); } console.log(onlyNumbers(arr1)); // 👉️ true console.log(onlyNumbers(arr2)); // 👉️ false console.log(onlyNumbers(arr3)); // 👉️ true
We use the isNaN function to determine if the passed in value can be converted to a number or not.
console.log(isNaN('test')); // 👉️ true console.log(isNaN('1')); // 👉️ false
An easy way to think about it is:
isNaN
(is Not a Number) function tries to convert the passed in array
element to a number and returns true
if it can't.!
operator, to check if all
elements in the array can be converted to numbers.