Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check to see if all values inside an array is a number

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.
like image 992
jyoon006 Avatar asked Aug 11 '15 20:08

jyoon006


2 Answers

The easiest is to use the every function of Array:

var res = array.every(function(element) {return typeof element === 'number';});
like image 105
njzk2 Avatar answered Sep 23 '22 21:09

njzk2


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>');
like image 36
Daniel A. White Avatar answered Sep 19 '22 21:09

Daniel A. White