search

Home  >  Q&A  >  body text

javascript - How to determine if all elements of an array are equal in js

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

仅有的幸福仅有的幸福2806 days ago867

reply all(7)I'll reply

  • phpcn_u1582

    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;
        }
    }

    reply
    0
  • phpcn_u1582

    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.

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-19 10:44:28

    function compare(array1, array2) 
    {
    (array1.length == array2.length) && array1.every(function(element, index) {
        return element === array2[index]; 
    })
    }

    reply
    0
  • 漂亮男人

    漂亮男人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
    }

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新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
             }

    reply
    0
  • 大家讲道理

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

    reply
    0
  • 迷茫

    迷茫2017-05-19 10:44:28

    How about I show off my wits?

    reply
    0
  • Cancelreply