我需要找到所有值都相等的数组。最快的方法是什么?我应该循环遍历它,然后比较值吗?

['a', 'a', 'a', 'a'] // true
['a', 'a', 'b', 'a'] // false

当前回答

你可以使用for循环:

function isEqual(arr) {
  var first = arr[0];
  for (let i = 1; i < arr.length; i++) {
    if (first !== arr[i]) {
      return false;
    }
  }
  return true;
}

其他回答

我喜欢的另一个很酷的解决方案是使用异或运算符:

console.log([5,5,5,5].reduce((a,b)=>a^b) == 0)
>> true
console.log([5,5,5,4].reduce((a,b)=>a^b) == 0)
>> false
**// Logical Solution:- Declare global array and one variable(To check the condition) whether all element of an array contains same value or not.**

    var arr =[];
    var isMatching = false;

    for(var i=0;i<arr.length;i++){
            if(String(arr[i]).toLowerCase()== "Your string to check"){
                isMatching=true;
                // Array has same value in all index of an array
            }
            else{
                isMatching=false;
                // Array Doesn't has same value in all index of an array
                break;
            }
        }
    // **Check isMatching variable is true or false**

        if(isMatching){ // True
            //If Array has same value in all index, then this block will get executed
        }
        else{ //False
            //If Array doesn't has same value in all index, then this block will get executed
        }

使用下划线/lodash的最短答案

function elementsEqual(arr) {
    return !_.without(arr, arr[0]).length
}

规范:

elementsEqual(null) // throws error
elementsEqual([]) // true
elementsEqual({}) // true
elementsEqual([1]) // true
elementsEqual([1,2]) // false
elementsEqual(NaN) // true

编辑:

或者更简短一点,受汤姆回答的启发:

function elementsEqual2(arr) {
    return _.uniq(arr).length <= 1;
}

规范:

elementsEqual2(null) // true (beware, it's different than above)
elementsEqual2([]) // true
elementsEqual2({}) // true
elementsEqual2([1]) // true
elementsEqual2([1,2]) // false
elementsEqual2(NaN) // true

在PHP中,有一个非常简单的解决方案,一行方法:

(count(array_count_values($array)) == 1)

例如:

$arr1 = ['a', 'a', 'a', 'a'];
$arr2 = ['a', 'a', 'b', 'a'];


print (count(array_count_values($arr1)) == 1 ? "identical" : "not identical"); // identical
print (count(array_count_values($arr2)) == 1 ? "identical" : "not identical"); // not identical

这是所有。

你可以用这个:

function same(a) {
    if (!a.length) return true;
    return !a.filter(function (e) {
        return e !== a[0];
    }).length;
}

该函数首先检查数组是否为空。如果是的话,它的值是相等的。 否则,它会过滤数组并获取与第一个不同的所有元素。如果没有=>这样的值,则数组只包含相等的元素,否则不包含。