0

I have an array:

    var cars = [
    {type:"Volvo", year:2016},
    {type:"Saab", year:2001},
    {type:"BMW", year:2010}]

and I want to sort cars object on type using this code

    function myFunction() {
       cars.sort(function(a, b){
           var x = a.type.toLowerCase();
           var y = b.type.toLowerCase();
           if (x < y) {return -1;}
           if (x > y) {return 1;}
           return 0;
       });
       displayCars(); // a function to output the result 
    }

x and y in this function is either saab, bww or volvo. How is it possible to compare (saab < bmw). I mean they are not numbers to be compared and return another number.

How does if conditional statements compares two strings rather than comparing numbers? and why does it has to return -1, 1 and zero?

4
  • 2
    return a.localCompare(b); if you need to compare strings. Commented Oct 25, 2018 at 18:57
  • @Ele But that does something different than a simple comparison? Commented Oct 25, 2018 at 19:15
  • javascript will convert alphabet to ascii code and compare the character by character. Commented Oct 25, 2018 at 19:16
  • 1
    @mehta-rohan There's nothing to "convert". A string already consists of code points. Commented Oct 25, 2018 at 19:22

1 Answer 1

0

Are you asking why this works?

If so, it works because JavaScript has some awareness of lexicographical order. B comes before S and S comes before V and so on.

-1 means that variable a should be moved one index lower than variable b.

1 means that variable a should be moved one index higher than variable b.

0 means that variable a should not be moved.

Sign up to request clarification or add additional context in comments.

Comments