我需要找到所有值都相等的数组。最快的方法是什么?我应该循环遍历它,然后比较值吗?
['a', 'a', 'a', 'a'] // true
['a', 'a', 'b', 'a'] // false
我需要找到所有值都相等的数组。最快的方法是什么?我应该循环遍历它,然后比较值吗?
['a', 'a', 'a', 'a'] // true
['a', 'a', 'b', 'a'] // false
当前回答
您可以将数组转换为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
其他回答
在JavaScript 1.6中,你可以使用Array.every:
function AllTheSame(array) {
var first = array[0];
return array.every(function(element) {
return element === first;
});
}
你可能需要一些完整性检查,例如当数组没有元素时。(此外,当所有元素都是NaN时,这将不起作用,因为NaN !== NaN,但这应该不是问题……对吗?)
当你使用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(…)的海报有最干净的解决方案。
你可以计算数组中不同值的数量,如果这个值是1,所有的条目都是相同的。
例子:
array = np.array([1, 2, 2, 3, 3])
set(array) # this gives the different values present in the array (1,2,3)
len(set(array)) # this returns 3, 3 different values in the array
在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
这是所有。
下划线_。isEqual(object, other)函数似乎可以很好地用于数组。当它检查是否相等时,数组中项目的顺序很重要。见http://underscorejs.org/ # isEqual。