2

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.

  • and why is 0,0,0 false? – Amit Joki Mar 04 '15 at 12:21
  • Because I am making a game, and it has to check if player 1 or player 2 owns all 3 of the objects. So 0 doesn't count. –  Mar 04 '15 at 12:22
  • try this http://stackoverflow.com/questions/14832603/check-if-all-values-of-array-are-equal but this only check if all are equal, then you have to check a[0] is 0 or 1/2 – TiGreX Mar 04 '15 at 12:24

4 Answers4

3

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;
}
siavolt
  • 6,869
  • 5
  • 24
  • 27
  • 1
    You could easily do `if(!array.length) return false;` instead of assigning `firstelement`, though. This is how I'd do it but I kind of like the `reduce` function below. – somethinghere Mar 04 '15 at 12:27
  • 1
    Semmantics, but you could just return false inside the foreach loop and save the effort of continuing to look when you already know it's false. – leigero Mar 04 '15 at 12:28
  • about if(!array.length) return false; i think we must check array to null, 0 or undifined – siavolt Mar 04 '15 at 12:31
  • If it ain't got no length, it ain't no array! Its also better to make javascript throw an error, but if you want to do everything I think it better to do `if(!array || !array.length) return false;`, check if something passed and if its an array by checking its `length`. – somethinghere Mar 04 '15 at 12:34
  • This script returns false if my array has "1","1","1" –  Mar 04 '15 at 12:35
  • Actually, it returns `undefined`. Heres a fix: initiliase result as `true` so it gets set to false when it finds a non-match. SO change the line ` var result;` to ` var result = true;` – somethinghere Mar 04 '15 at 12:38
  • 1
    Okay, thats good I guess. I cant see your updated every second :) Your scripts works though, and is easily understood. Me like. – somethinghere Mar 04 '15 at 12:40
  • 1
    This is exactly what I was trying to do. Thank you. –  Mar 04 '15 at 12:44
2

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;
}
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • 3
    Theres always someone suggesting `regex` patterns for everything :) – somethinghere Mar 04 '15 at 12:26
  • @somethinghere When it makes your work easy and more readable, why not? – Amit Joki Mar 04 '15 at 12:27
  • I am kind of new to Javascript, so how can I make this script read my array? Where do I put the array name. –  Mar 04 '15 at 12:28
  • I've never found regex to be "more readable" but easier, sure. – leigero Mar 04 '15 at 12:29
  • @leigero well, if you know em, they're easier to read. ^ is beginning, $ is the end, (1|2) means either one or two and `+` means more than once till the end. Regexes aren't readable only when they're kinda complex. – Amit Joki Mar 04 '15 at 12:31
  • I'm in favour of that solution, but actually @somethinghere has a point. For instance, your regex is invalid ;) It passes for [1,2,1]. Something like `/(^1+$)|(^2+$)/` suits better. – kamituel Mar 04 '15 at 12:31
  • @amitjoki Mostly because I think that `regex` looks complicated, making an easy task harder to debug, and otherwise because regex is quite performance heavy. I mostly use them in large chunks of text. But its always interesting to see that someone always finds a way to use them, even for mundane tasks :) Joost, you have to join your array together (`array.join('')`, which turns it into a string); – somethinghere Mar 04 '15 at 12:31
  • 1
    @somethinghere - true, but for this particular use, other options are either loop over an array, or use `reduce`/`filter` in some non-obiovus ways. Regex actually is pretty readable, when compared to other options. – kamituel Mar 04 '15 at 12:33
  • @kamituel I have to disagree here, `regex` is a very specific syntax. I think it better to loop over the array as it's more human-readable, and if you ever want to do anything else you can easily extend it. Don't get me wrong, I like the solution, but I find it harder to parse personally. – somethinghere Mar 04 '15 at 12:35
  • Regex is very specific syntax?? It's common in *most* of the cases.(Only lack of lookbehinds in some flavors). – Amit Joki Mar 04 '15 at 12:37
  • @amitjoki compared to programming itself, regex it a specific syntax. Contrary to what you think, for most cases regex it a bit more cumbersome than a human parseable solution. But lets not turn this into an argument, like I said, its nice there always a solution with regex, I just think that people just picking up programming for the first time are better off learning to loop than trying to understand regex. – somethinghere Mar 04 '15 at 12:40
  • @somethinghere you're entitled to your opinion but learning regex once will help you in many languages. Also it's easy to read for those who know it. The above regex is *fairly* easy too. But yeah, you've to learn the basics. – Amit Joki Mar 04 '15 at 12:47
  • @somethinghere I found out the regex solution was way slow. So removed that and hence used looping as you thought was the best. It is indeed fastest. – Amit Joki Mar 04 '15 at 13:00
  • @amitjoki Yeah, thats what I though. Regex is great for parsing large documents as the performance hit is less noticeable, but when parsing tiny strings its quite heavy. :) – somethinghere Mar 04 '15 at 13:20
  • @somethinghere pardon me for using regex, Sir :-) – Amit Joki Mar 04 '15 at 13:22
0

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
0

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];
})
kamituel
  • 34,606
  • 6
  • 81
  • 98