Check if the values in an array are all the same or all different

6

I wanted some function that would return TRUE when all values within an array were equal or all were different, and return FALSE if they were not all equal and not all different. If you have not understood, I'll explain with examples:

Ex:
If I have the following 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 or all different 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?

    
asked by anonymous 29.07.2015 / 18:37

3 answers

6

I filtered the array by removing the duplicates. If only one element remains, all are equal. If the size of the array is the same, all are 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; 
}
    
29.07.2015 / 19:20
3

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
    
29.07.2015 / 18:57
0
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.

    
29.07.2015 / 19:02