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 ?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With