JSFiddle - React, Tailwind, and code Playground
by Graham Fairweather
JavaScript
var x = [
{
"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",
}
];
function sorter(array, funcs, orders) {
funcs = funcs || {};
orders = orders || {};
array.sort(funcs.general);
if (Array.isArray(orders.top)) {
orders.top.slice().reverse().forEach(function(value) {
array.sort(funcs.top.bind(value));
});
}
if (Array.isArray(orders.bottom)) {
orders.bottom.forEach(function(value) {
array.sort(funcs.bottom.bind(value));
});
}
return array;
}
sorter(x, {
general: function (a, b) {
return a.destination_country_name.localeCompare(b.destination_country_name);
},
top: function (a, b) {
return +(!b.destination_country_name.localeCompare(this));
},
bottom: function (a, b) {
return +(!a.destination_country_name.localeCompare(this));
}
}, {
top: ['Ireland', 'United Kingdom', 'United States'],
bottom: ['Everywhere Else']
});
console.log(JSON.stringify(x, ['destination_country_name']));