I need a way to check if an array only contains numbers. For example
var a = [1,2,3,4] should pass and give true boolean
whereas var b = [1,3,4,'a'] should give false
I tried forEach() function as
a.forEach(function(item, index, array) {
if(!isNaN(item)) {
array.unshift("-");
}
}); //console.log of this will give array a = ["-","-","-","-", 1,2,3,4]
but since, forEach() iterates through every index in the array, and since every item for var a is a number, it unshifts to array every item it iterates. I need a way to only unshift "-" once if the whole array value is a number.
I also tried to do with test()
var checkNum = /[0-9]/;
console.log(checkNum.test(a)) //this gives true
console.log(checkNum.test(b)) // this also gives true since I believe test
//only checks if it contains digits not every
//value is a digit.
The easiest is to use the every
function of Array
:
var res = array.every(function(element) {return typeof element === 'number';});
Try something like this:
var a = arr.reduce(function(result, val) {
return result && typeof val === 'number';
}, true);
function areNumbers(arr) {
document.write(JSON.stringify(arr) + ':')
return arr.reduce(function(result, val) {
return result && typeof val === 'number';
}, true);
}
document.write(areNumbers([1, 2, 3, 4]) + '<br>');
document.write(areNumbers([1, 2, 3, '4']) + '<br>');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With