Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if each item in an array is identical in 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?

like image 958
Nick Avatar asked Mar 10 '12 13:03

Nick


People also ask

How do you check if every element in an array is the same?

To check if all values in an array are equal:Use the Array. every() method to iterate over the array. Check if each array element is equal to the first one. The every method only returns true if the condition is met for all array elements.

How do you check if an array of objects has duplicate values in JavaScript?

Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.

How do you check if an array is equal to another array in JavaScript?

To conclude, to compare arrays to check for equality, Lodash's isEqual() function is the way to go if you need all the bells and whistles of checking that objects have the same class. The JSON. stringify() approach works well for POJOs, just make sure you take into account null.

How can you tell if an array is identical?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.


2 Answers

function identical(array) {
    for(var i = 0; i < array.length - 1; i++) {
        if(array[i] !== array[i+1]) {
            return false;
        }
    }
    return true;
}
like image 88
Dogbert Avatar answered Sep 23 '22 15:09

Dogbert


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.

like image 43
pimvdb Avatar answered Sep 23 '22 15:09

pimvdb