Compruebe si cada elemento de una matriz es idéntico en JavaScript

I need to test whether each item in an array is identical to each other. For example:

var list = ["l","r","b"]

Should evaluate as false, because each item is not identical. On the other hand this:

var list = ["b", "b", "b"]

Should evaluate as true because they are all identical. What would be the most efficient (in speed/resources) way of achieving this?

preguntado el 10 de marzo de 12 a las 13:03

10 Respuestas

function identical(array) {
    for(var i = 0; i < array.length - 1; i++) {
        if(array[i] !== array[i+1]) {
            return false;
        }
    }
    return true;
}

respondido 22 mar '16, 08:03

I opted for this solution, thanks. Pimvdb had a very elegant solution with array.every but that would of required adding a big chunk of code (for non-ES5 compliant browser support) to an already large document for just one instance of .every so I opted for this instead. - Nick

Your solution made the most sense to me. However, I'd change the "!=" to "!==" because your solution returns true in the following array [1,1,1,1,1,1,"1"] where the last character is a string. - Joffrey Baratheon

I'd like to see something similar but for objects. - sombrereroloco

Nice solution in traditional way. ES5 introduced Array.every(), which could be used for one linear solution as: stackoverflow.com/questions/9646943/… - Chang

In ES5, you could do:

arr.every(function(v, i, a) {
   // first item: nothing to compare with (and, single element arrays should return true)
   // otherwise:  compare current value to previous value
   return i === 0 || v === a[i - 1];
});

.every does short-circuit as well.

respondido 10 mar '12, 13:03

Nice, didn't know this existed and going to start using this myself. Just adding a pointer to the docs for array.every developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… - Shane

Thanks, that's a very elegant solution. I went for Dogberts solution in the end to avoid adding the array.every code to support older browsers - but in principle this would have worked nicely. - Nick

Here no need to compare each predecessor with the current value i.e. v===a[i-1]. Anyways a you can find one linear solution at: stackoverflow.com/a/54826946/8958729 - Chang

You could always do a new Set, and check the length.

var set1 = [...new Set(list)].length === 1;

Respondido 10 Abr '20, 00:04

The one line answer is:

arr.every((val, ind, arr) => val === arr[0]);

Puedes mirar en Array.every para ver más información.

Nota:

  1. Array.every está disponible ES5 adelante.
  2. Este método regresa true for any condition put on an empty array.
  3. Sintaxis: arr.every(callback[, thisArg]) or array.every(function(currentValue, index, arr), thisValue)
  4. It does not change the original array
  5. The execution of every() is en cortocircuito. Tan pronto como cada() finds an array element that doesn't match the predicate, it immediately returns false and doesn't iterate over the remaining elements

respondido 20 nov., 20:02

function matchList(list) {
  var listItem = list[0];

  for (index in list) {
    if(list[index] != listItem {
       return false;
    }
  }

  return true;
}

respondido 10 mar '12, 13:03

it will fail at the last element of the array. - gonzalo larralde

var list = ["b", "b", "b"];
var checkItem = list[0];
var isSame = true;
for (var i = 0; i < list.length; i++) {
  if (list[i] != checkItem) {
    isSame = false;
    break;
  }
}
return isSame;

respondido 10 mar '12, 13:03

Just return false when you first encounter it. - jivings

Yeah, I wasn't sure if the OP wanted it for use later, or returned in a function. - waynn lue

You can use every() for one linear solution. Ref: stackoverflow.com/a/54826946/8958729 - Chang

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- begin snippet: js hide: false console: true babel: false -->

Respondido el 11 de enero de 19 a las 07:01

arr.every(i=>i==arr[0]) //will return true if all items in arr are identical

Respondido el 12 de enero de 21 a las 14:01

My suggestion would be to remove duplicates (check out La forma más sencilla de encontrar valores duplicados en una matriz de JavaScript), and then check to see if the length == 1. That would mean that all items were the same.

contestado el 23 de mayo de 17 a las 13:05

That would be O(n^2) (or O(n log n) depending on the sorting algorithm). Too slow. - Dogberto

I was actually suggesting the second answer (should have specified), that remove duplicates without sorting. - Kory Sharp

function allEqual(list)
{
    if(list.length == 0 || list.length == 1)
    {
      return true;
    }

    for (index in list) {
    if(list[index] != list[index+1] {
       return false;
    }
  }

  return true;

}

respondido 10 mar '12, 13:03

Like my first answer: it will fail at the last element of the array. - jivings

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.