javascript - How to determine if all elements of an array are equal in js
仅有的幸福
仅有的幸福 2017-05-19 10:42:28
0
7
765

How does js determine that all elements of an array are equal

仅有的幸福
仅有的幸福

reply all(7)
phpcn_u1582

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_u1582

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.

给我你的怀抱
function compare(array1, array2) 
{
(array1.length == array2.length) && array1.every(function(element, index) {
    return element === array2[index]; 
})
}
漂亮男人
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
}
曾经蜡笔没有小新

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
         }
大家讲道理

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;
迷茫

How about I show off my wits?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!