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

['a', 'a', 'a', 'a'] // true
['a', 'a', 'b', 'a'] // 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
        }

其他回答

您可以将数组转换为Set并检查其大小

对于基元数组条目,即number, string:

const isArrayWithEqualEntries = array => new Set(array).size === 1

如果对象数组中有一些字段需要测试是否等价,则输入id:

const mapper = ({id}) => id
const isArrayWithEqualEntries = array => new Set(array.map(mapper)).size === 1

在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

这是所有。

你可以使用Array.prototype让这一行代码做你想做的事情。每一个对象。和ES6箭头函数:

const all = arr => arr.every(x => Object.is(arr[0], x));

如果你已经在使用underscore.js,那么这里有另一个使用_.uniq的选项:

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

_。Uniq返回数组的无重复版本。如果所有值都相同,则长度为1。

正如评论中提到的,假设你希望一个空数组返回true,那么你也应该检查这种情况:

function allEqual(arr) {
    return arr.length === 0 || _.uniq(arr).length === 1;
}

你可以用这个:

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

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