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?

1 Answers1

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.

Drew Knab
  • 54
  • 4