Click here to Skip to main content
16,019,740 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
JavaScript
<!DOCTYPE html>



<p>Click the buttons to sort car objects on type.</p>

Sort

<p id="demo"></p>
<p id="dd"> </p>
<p id="ddd"> </p>



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

displayCars();

function myFunction() {
    cars.sort(function(a, b){
        var x = a.type.toLowerCase();
        var y = b.type.toLowerCase();
        document.getElementById("dd").innerHTML= x;
        document.getElementById("ddd").innerHTML = y;
        if (x &lt; y) {return 0;}
        if (x > y) {return 1;}
        });
    displayCars();
}

function displayCars() {
  document.getElementById("demo").innerHTML =
  cars[0].type + " " + cars[0].year + "<br>" +
  cars[1].type + " " + cars[1].year + "<br>" +
  cars[2].type + " " + cars[2].year;
}


What I have tried:

I just want to know about why .tolowercase is used here with return (0) or (1).
Posted
Updated 30-Apr-17 3:58am
v3

1 solution

tolowercase is used to ensure that the comparison is always comparing the same values: in computer terms, "Hello" is not the same as "hello" because upper and lower case characters are not the same, 'H' is not the same characters as 'h'.

The return values indicates the sort order: 0 means the second parameter is the largest, 1 means the first is. If they are both the same, a random value it returns, and will cause bugs later on...
 
Share this answer
 
v2
Comments
Thenewbieee 30-Apr-17 5:03am    
I still can't get it, can you please explain the lines of myfunction() ?
Thenewbieee 30-Apr-17 5:05am    
Is it sorting objects on the basis of alphabetical order?
OriginalGriff 30-Apr-17 5:27am    
Yes.
Thenewbieee 30-Apr-17 5:31am    
How 0 and 1 works? Can you please explain that?
Thenewbieee 30-Apr-17 5:32am    
Isn't is comparing just two values? what about the third value?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900