user4051844
user4051844

Reputation:

Check if multiple array values are equal

So I have an array which has 3 possible values: 0, 1 or 2

var a = [0,0,0];

I want to check if a[0], a[1], and a[2] all have the equal value of "1" or "2". How can I do this?

So 0,0,0 would return false, 1,2,1 false, but 1,1,1 or 2,2,2 would be true.

Upvotes: 2

Views: 1018

Answers (4)

Amit Joki
Amit Joki

Reputation: 59232

The regex solution was slow as shown in http://jsperf.com/looping-vs-regex. SO came up with this.

function checkArr(arr){
   var f = arr[0];
   if(f == 0) return false;
   for(var i = 0; i < arr.length; i++)
      if(arr[i] != f) return false;
   return true;
}

Upvotes: 2

kamituel
kamituel

Reputation: 35950

Another apporach, without looping or regexes:

var arr = [1,2,1];
arr.every(function (el) {
  return (el === 1 || el === 2) && el === arr[0];
})

Or, with .some instead of .every:

!arr.some(function (el) {
  return (el !== 1 && el !== 2) || el !== arr[0];
})

Upvotes: 0

user2575725
user2575725

Reputation:

Try this:

var validate = function(arr) {
    var s = 0;
    var i = l = arr.length;
    while(i --)
        s += arr[i];
    return l === s || (2 * l) === s;
};

console.log(validate([0,0,0]));//false
console.log(validate([1,2,1]));//false
console.log(validate([2,2,2]));//true
console.log(validate([1,1,1]));//true
console.log(validate([2,2,2,2,2]));//true

Upvotes: 0

siavolt
siavolt

Reputation: 7067

Try this:

function checkArray(array){
    var firstElement = array[0];
    if(!firstElement) return false;

    var result = true;

    array.forEach(function(elem){
        if(elem != firstElement) result = false;
    });

    return result;
}

Upvotes: 3

Related Questions