Sorting objects by property values

2020-01-24 19:49发布

How to implement the following scenario using Javascript only:

  • Create a car object with properties (top speed, brand, etc.)
  • Sort a list of cars ordered by those properties

7条回答
甜甜的少女心
2楼-- · 2020-01-24 20:41

Let us say we have to sort a list of objects in ascending order based on a particular property, in this example lets say we have to sort based on the "name" property, then below is the required code :

var list_Objects = [{"name"="Bob"},{"name"="Jay"},{"name"="Abhi"}];
Console.log(list_Objects);   //[{"name"="Bob"},{"name"="Jay"},{"name"="Abhi"}]
    list_Objects.sort(function(a,b){
        return a["name"].localeCompare(b["name"]); 
    });
Console.log(list_Objects);  //[{"name"="Abhi"},{"name"="Bob"},{"name"="Jay"}]
查看更多
登录 后发表回答