Check whether the values of an array are all the same or all different

Asked

Viewed 5,917 times

6

  I wanted some function that returned TRUE when all values within an array were equal or if all were different, and returned FALSE if they were not all the same and not all different. In case you don’t understand, I’ll explain with examples:

Ex:
 If I have the following(s) array(s) for verification:

var arr = ['xx','xx','xx']; //(todos iguais)
     //ou
var arr = ['xx','yy','zz']; //(todos diferentes)

The function would return TRUE, but if it were an array in which the values are not all equal not all different it would return FALSE, as in the following situation:

var arr = ['xx','xx','zz']; //(Os valores não todos iguais, e nem todos diferentes)

Eai? Does anyone have any idea how I can do this?

  • What have you tried?

3 answers

7


I have filtered the array by removing duplicates. If only one element is left, they are all the same. If the array size is the same, they are all different.

function todosIguaisOuDiferentes(array) {
    var filtrado = array.filter(function(elem, pos, arr) {
        return arr.indexOf(elem) == pos;
    });

    return filtrado.length === 1 || filtrado.length === array.length; 
}
  • 1

    +1 ... Code readable, short and intelligent.

  • Vlw, it worked here! : )

2

Array.prototype.allValuesSame = function() {
  for (var i = 1; i < this.length; i++) {
    if (this[i] !== this[0])
      return false;
  }
  return true;
}

var arr = ['xx', 'xx', 'xx']; //(todos iguais)
var arr2 = ['xx', 'yy', 'zz']; //(todos diferentes)

console.log(arr.allValuesSame()); // true
console.log(arr2.allValuesSame()); // false

  • When they’re all different you have to return true too, from what I understand.

  • 1

    Must return true if all are equal or all are different. This answer is incorrect.

  • I got it, I forgot that detail, I’m going to edit this answer.

1

function CheckArray (a) {
    if (a.length == 1)
        return true;

    var result = false;

    // Verifica se são todos iguais
    for(var i = a.length - 1; i >= 0; i--) {
        if (!(a[0] === a[i])) {
            result = false;
            break;
        } else {
            result = true;
        }
    }
    if (result)
        return true;

    // Verifica se são todos diferentes
    result = true;
    for (var i = a.length - 1; i >= 0; i--) {
        // Caso o indexOf e o lastIndexOf sejam diferentes, isso indica que há duas ocorrências e portanto não são todos diferentes.
        if (a.indexOf(a[i]) != a.lastIndexOf(a[i])) {
            result = false;
            break;
        }
    }

    return result;
}

It’s not exactly fancy code, but from what I’ve tested it works.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.