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
Possibly not the most efficient method but it is ES3, doesn't require any libraries, and is fairly easy to understand. Also assuming you wanted to sort alphabetically on destination_country_name
Javascript
// where x is your array of objects
x.sort(function (a, b) {
// sorts everything alphabetically
return a.destination_country_name.localeCompare(b.destination_country_name);
}).sort(function (a, b) {
// moves only this to country to top
return +(!b.destination_country_name.localeCompare('United States'));
}).sort(function (a, b) {
// moves only this to country to top
return +(!b.destination_country_name.localeCompare('United Kingdom'));
}).sort(function (a, b) {
// moves only this to country to top
return +(!b.destination_country_name.localeCompare('Ireland'));
}).sort(function (a, b) {
// moves only this to country to bottom
return +(!a.destination_country_name.localeCompare('Everywhere Else'));
});
console.log(JSON.stringify(x, ['destination_country_name']));
Output
[{"destination_country_name":"Ireland"}, {"destination_country_name":"United Kingdom"}, {"destination_country_name":"United States"}, {"destination_country_name":"France"}, {"destination_country_name":"Spain"}, {"destination_country_name":"Everywhere Else"}]
On jsFiddle
We could even go a step further and use the above example to make a reusable function, like.
Javascript
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']
});
On jsFiddle
And now you can easily sort on different attributes by parsing in different compare functions, and define values that should be at the top or bottom.
I used ECMA5 methods but you could just as easily make it with ECMA3.