Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort json object based on multiple values with different sorting order [duplicate]

I have following JSON Object

   var data1 =  [
    {id: "1", name: "b", lastname: "y", marks: "10"},
    {id: "1", name: "a", lastname: "x", marks: "20"},
    {id: "2", name: "a", lastname: "x", marks: "30"},
    {id: "2", name: "b", lastname: "x", marks: "40"},
    {id: "2", name: "c", lastname: "z", marks: "60"},
    {id: "3", name: "d", lastname: "x", marks: "50"},
    {id: "3", name: "a", lastname: "c", marks: "70"}    
  ];

I what to sort this object based on different condition like-

first sort by name in asc order

than sort result by last name in desc order

than sort rsult by marks in desc order

fields and their order type is generated dynamically by web page.

*** here sort feilds and theire types are not fixed it may be anything like name asc, marks asc, lastname desc or marks desc, lastname desc, name asc

Can any one help me to suggest any jquery, java script plugin or function ?

like image 854
Anupam Sharma Avatar asked Nov 09 '22 18:11

Anupam Sharma


1 Answers

You can use sort to achieve this if you implement you own custom sort function. Something like this:

function sortFunc(a, b) {
    if (a.name < b.name)  return -1;
    else if (a.name > b.name)  return 1;
    else {
        if (a.lastname < b.lastname)  return 1;
        else if (a.lastname > b.lastname)  return -1;
        else {
            if (a.marks < b.marks) return 1;
            else if (a.marks > b.marks) return -1;
        }
        return 0;
    }
}

console.log(data1.sort(sortFunc));

Example fiddle

like image 51
Rory McCrossan Avatar answered Nov 14 '22 22:11

Rory McCrossan