I have an array of objects returning from an API call which I need to sort into a specific format.
I\'m trying to organise the destination_country_id
alphab
You can give every object a 'sort-order' property. Specify the known first 3 and the last, and give all the others the same value, greater than the first three and less than the last. Then sort the array- first by sort-order, and then alphabetically;
var arr= [{ "destination_country_id": null, "primary_cost": "9.50", "region_id": null, "destination_country_name": "Everywhere Else", },{ "destination_country_id": 105, "primary_cost": "8.00", "region_id": null, "destination_country_name": "United Kingdom", },{ "destination_country_id": 209, "primary_cost": "9.50", "region_id": null, "destination_country_name": "United States", },{ "destination_country_id": 123, "primary_cost": "5.00", "region_id": null, "destination_country_name": "Ireland", },{ "destination_country_id": 185, "primary_cost": "5.00", "region_id": null, "destination_country_name": "France", },{ "destination_country_id": 145, "primary_cost": "5.00", "region_id": null, "destination_country_name": "Spain", }]
var s= "destination_country_name",
order= ["Ireland", "United Kingdom",
"United States", "Everywhere Else"];
arr.forEach(function(itm){
var i= order.indexOf(itm[s]);
if(i!= -1) itm.sort_order= i== 3? 1e50: i;
else itm.sort_order= 10;
});
arr.sort(function(a, b){
var d= a.sort_order- b.sort_order;
if(d===0){
if(a[s]=== b[s]) return 0;
return a[s]>b[s]? 1: -1;
}
return d;
});
JSON.stringify(arr)
/* returned value: (String)[{
"destination_country_id": 123, "primary_cost": "5.00", "region_id": null,
"destination_country_name": "Ireland", "sort_order": 0
},{
"destination_country_id": 105, "primary_cost": "8.00", "region_id": null,
"destination_country_name": "United Kingdom", "sort_order": 1
},{
"destination_country_id": 209, "primary_cost": "9.50", "region_id": null,
"destination_country_name": "United States", "sort_order": 2
},{
"destination_country_id": 185, "primary_cost": "5.00", "region_id": null,
"destination_country_name": "France", "sort_order": 10
},{
"destination_country_id": 145, "primary_cost": "5.00", "region_id": null,
"destination_country_name": "Spain", "sort_order": 10
},{
"destination_country_id": null, "primary_cost": "9.50", "region_id": null,
"destination_country_name": "Everywhere Else", "sort_order": 1e+50
}
]
*/