18
votes

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?

10

10 Answers

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

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.

5
votes

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

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

The one line answer is:

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

You can look into Array.every for more details.

Note:

  1. Array.every is available ES5 onwards.
  2. This method returns true for any condition put on an empty array.
  3. Syntax: 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 short-circuited. As soon as every() finds an array element that doesn't match the predicate, it immediately returns false and doesn't iterate over the remaining elements
2
votes
function matchList(list) {
  var listItem = list[0];

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

  return true;
}
1
votes
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;
1
votes

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

<!-- begin snippet: js hide: false console: true babel: false -->
1
votes
arr.every(i=>i==arr[0]) //will return true if all items in arr are identical
0
votes

My suggestion would be to remove duplicates (check out Easiest way to find duplicate values in a JavaScript array), and then check to see if the length == 1. That would mean that all items were the same.

0
votes
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;

}