How does js determine that all elements of an array are equal
phpcn_u15822017-05-19 10:44:28
Judging that all are equal is equivalent to judging that one of them is not equal,
function isAllEqual(array){
if(array.length>0){
return !array.some(function(value,index){
return value !== array[0];
});
}else{
return true;
}
}
phpcn_u15822017-05-19 10:44:28
The questioner did not say it is a simple array; if the array elements include Object, etc., then the above answer will basically fail. Then the problem actually becomes how to judge that two Objects are equal, and then it involves recursion... In short, it is not that simple, so I won’t go into details about the claw machine code.
给我你的怀抱2017-05-19 10:44:28
function compare(array1, array2)
{
(array1.length == array2.length) && array1.every(function(element, index) {
return element === array2[index];
})
}
漂亮男人2017-05-19 10:44:28
function test (arr) {
return arr.reduce((o, item) => (o.result = o.result && item === o.prev, o.prev = item, o), { result: true, prev: arr[0] }).result
}
曾经蜡笔没有小新2017-05-19 10:44:28
Isn’t this something that can be solved with just one cycle?
var equals=function(arr){
var bool=true;
for(var i=1,len=arr.length;i<len;i++){
if(arr[i]!==arr[0]){bool=false}
}
return bool
}
大家讲道理2017-05-19 10:44:28
If you want to consider objects, you can refer to Lodash’s isEqual
Only simple types are considered:
var arr = [/*elements*/];
var isAllEqual = new Set(arr).size === 1;