In this tutorial learn how to sorting an array of objects using javascript function sort(),
lets say your array doesn't contain just simple numeric or string values, but objects with properties instead:
The
Sort by user age
Lets start by sorting the user array by their ages (ascending). Here's the comparison function that does this:
Sort by user Name
Lets start by sorting the user array by their name (ascending). Here's the comparison function that does this:
lets say your array doesn't contain just simple numeric or string values, but objects with properties instead:
The
sort()
method can be used to sort the array based on the values of one of these properties, such as sorting the array by age.Sort by user age
Lets start by sorting the user array by their ages (ascending). Here's the comparison function that does this:
<body onload="javascript:sort_arr()"> <script type="text/javascript"> function sort_arr() { var user=[] user[0]={name:"Ghanshyam", age:30} user[1]={name:"Nakiya", age:15} user[2]={name:"Jack", age:50} user[3]={name:"Taylor", age:58} user.sort(function(a, b){ return a.age-b.age; }) alert(JSON.stringify(user)); } </script> </body>
Sort by user Name
Lets start by sorting the user array by their name (ascending). Here's the comparison function that does this:
<body onload="javascript:sort_arr()"> <script type="text/javascript"> function sort_arr() { var user=[] user[0]={name:"Ghanshyam", age:30} user[1]={name:"Nakiya", age:15} user[2]={name:"Jack", age:50} user[3]={name:"Taylor", age:58} user.sort(function(a, b){ var A=a.name.toLowerCase(), B=b.name.toLowerCase() if (A < B) //sort string ascending return -1 if (A > B) return 1 return 0 //default return value (no sorting) }) alert(JSON.stringify(user)); } </script> </body>
Sorting by name its helping me alot
ReplyDeleteHow to sort an array based on another array in javascript?
ReplyDelete