我需要找到所有值都相等的数组。最快的方法是什么?我应该循环遍历它,然后比较值吗?
['a', 'a', 'a', 'a'] // true
['a', 'a', 'b', 'a'] // false
我需要找到所有值都相等的数组。最快的方法是什么?我应该循环遍历它,然后比较值吗?
['a', 'a', 'a', 'a'] // true
['a', 'a', 'b', 'a'] // false
当前回答
您可以将Array转换为Set。如果Set的大小等于1,则数组中的所有元素都相等。
function allEqual(arr) {
return new Set(arr).size == 1;
}
allEqual(['a', 'a', 'a', 'a']); // true
allEqual(['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
这是所有。
**// 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
}
你可以使用数组。每个if支持:
var equals = array.every(function(value, index, array){
return value === array[0];
});
循环的替代方法可以是类似sort的东西
var temp = array.slice(0).sort();
var equals = temp[0] === temp[temp.length - 1];
或者,如果项目像问题,一些肮脏的东西,比如:
var equals = array.join('').split(array[0]).join('').length === 0;
同样适用。
你可以计算数组中不同值的数量,如果这个值是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
你可以使用for循环:
function isEqual(arr) {
var first = arr[0];
for (let i = 1; i < arr.length; i++) {
if (first !== arr[i]) {
return false;
}
}
return true;
}