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

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

当前回答

在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

这是所有。

其他回答

当你使用ES6箭头函数语法时,另一个有趣的方式是:

x = ['a', 'a', 'a', 'a']
!x.filter(e=>e!==x[0])[0]  // true

x = ['a', 'a', 'b', 'a']
!x.filter(e=>e!==x[0])[0] // false

x = []
!x.filter(e=>e!==x[0])[0]  // true

当你不想为数组(x)重用变量时:

!['a', 'a', 'a', 'a'].filter((e,i,a)=>e!==a[0])[0]    // true

IMO之前使用array.every(…)的海报有最干净的解决方案。

公认的答案很好,但我想补充一点。对我来说,使用===行不通,因为我在比较对象数组的数组,但是在我的应用程序中,我一直在使用我强烈推荐的fast-deep-equal包。这样,我的代码看起来就像这样:

let areAllEqual = arrs.every((val, i, arr) => equal(val, arr[0]) );

我的数据是这样的:

[  
  [
    {
      "ID": 28,
      "AuthorID": 121,
      "VisitTypeID": 2
    },
    {
      "ID": 115,
      "AuthorID": 121,
      "VisitTypeID": 1
    },
    {
      "ID": 121,
      "AuthorID": 121,
      "VisitTypeID": 1
    }
  ],
  [
    {
      "ID": 121,
      "AuthorID": 121,
      "VisitTypeID": 1
    }
  ],
  [
    {
      "ID": 5,
      "AuthorID": 121,
      "VisitTypeID": 1
    },
    {
      "ID": 121,
      "AuthorID": 121,
      "VisitTypeID": 1
    }
  ]
]

这个作品。通过使用prototype在Array上创建一个方法。

if (Array.prototype.allValuesSame === undefined) {
  Array.prototype.allValuesSame = function() {
    for (let i = 1; i < this.length; i++) {
      if (this[i] !== this[0]) {
        return false;
      }
    }
    return true;
  }
}

这样调用它:

let a = ['a', 'a', 'a'];
let b = a.allValuesSame(); // true
a = ['a', 'b', 'a'];
b = a.allValuesSame();     // false

这可能会起作用,你也可以使用注释代码,这也适用于给定的场景。

函数isUniform () { var arrayToMatch = [1,1,1,1,1]; var temp = arrayToMatch[0]; console.log(临时); /*返回arrayToMatch.every(函数(检查){ 返回检查== temp; }); * / var bool; arrayToMatch.forEach(函数(检查){ Bool =(check == temp); }) console.log (bool); } isUniform ();

你可以用这个:

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

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