console.log([2,6,10]>[2,10,0]); 

Return true , why?

    3 answers 3

    Because their string representations are compared:

     console.log( [2, 6, 10].toString(), [2, 10, 0].toString(), [2, 6, 10] > [2, 10, 0] ); 

    Why then is [1,1,1] not identical and not equal to [1,1,1] ?

    Why not equal? Equal to:

     var a = [1,1,1]; var b = [1,1,1]; console.log(!(a > b) && !(a < b)); 


    And how to compare them then?

    Elementally.

    • And how to compare them then? - Kopkan pm
    • @ Kopkan First you need to define what it means: "one array is more / less than another." But I already guess. - Igor
    • Why then is [1,1,1] not identical and not equal to [1,1,1] ? - doox911 9:31 pm
    • @ doox911 Added in response. - Igor
    • And here is console.log([0,0,0]===[0,0,0]); VM1467:1 false console.log([0,0,0]===[0,0,0]); VM1467:1 false - chrome console - doox911

    When comparing to> and <objects are reduced to primitives - in the case of arrays, these are strings, in which all elements of the array are listed separated by commas. Therefore, [2,6,10]>[2,10,0] is the same as "2,6,10">"2,10,0" , and the lines are compared lexicographically. The first 2 characters are 2, are the same here, but then 6 and 1 are compared further - it is obvious that the first one is larger - that’s true.

    If you want to compare arrays element by element, you need to write your own function that compares them in a loop.

    PS: A little off topic, but can be useful .

    • About your comment to my deleted answer. Are given. Are brought to logical type, processed, and returns one of the operands (already in the form in which it was transmitted). - smellyshovel

    This function will return the number (starting from 1) of the larger array and 0 if they are equal

     function compareArrays(m1, m2) { for(let i=0; i<m1.length && i<m2.length; i++) { if(m1[i]>m2[i]){ return 1; } if(m1[i]<m2[i]){ return 2; } } if(m1.length>m2.length){return 1;} if(m1.length<m2.length){return 2;} if(m1.length==m2.length){return 0;} return false; } console.log(compareArrays([5,6,4], [5,10,0])); 

    • @meine, he actually wrote it ... - Qwertiy
    • @Qwertiy, it turned out awkwardly) - meine