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?