Reputation: 973
I have multiple json arrays inside an array. I need to sort the json arrays in ascending order by name first and item.
var result = [[{"name":"james","item":"car"....],[{"name":"adrian","item":"car"....}],[{"name":"adrian","item":"truck"...}]]
result.sort(function(a, b) {
return (a.name).localeCompare(b.name) || (a.item).localeCompare(b.item);
});
Output desired: [ [{"name":"adrian","item":"car"}],[{"name":"adrian","item":"truck"}],[{"name":"james","item":"car"}] ]
Upvotes: 1
Views: 189
Reputation: 3071
Your arguments to sort
function is an array. Please post complete sample to give you more accurate result. With the above sample below code will work.
var result = [[{ "name": "james", "item": "car" }], [{ "name": "adrian", "item": "car" }], [{ "name": "adrian", "item": "truck" }]]
result.sort(function (a, b) {
return a[0].name.localeCompare(b[0].name) || a[0].item.localeCompare(b[0].item);
});
Upvotes: 1
Reputation: 1391
I think you were close. Since it's arrays in array, use that
var result = [[{"name":"james","item":"car"}],[{"name":"adrian","item":"car"}],[{"name":"adrian","item":"truck"}]];
result.sort(function(a, b) {
return (a[0].name).localeCompare(b[0].name) || (a[0].item).localeCompare(b[0].item);
});
And test result with :
console.log(JSON.stringify(result));
=>
[[{"name":"adrian","item":"car"}],[{"name":"adrian","item":"truck"}],[{"name":"james","item":"car"}]]
Upvotes: 2