I am trying to sort an array in JavaScript, but I want one specific item to always be first in the sort, and another specific item to always be last:
var Person= [{
"Country": "Japan",
"Name": "user1"
}, {
"Country": "Spain",
"Name": "user24"
}, {
"Country": "Usa",
"Name": "user1"
}, {
"Country": "Brazil",
"Name": "user1"
}];
Here is my compare function:
function compare(a,b) {
if (a.Country< b.Country)
return -1;
if (a.Country> b.Country)
return 1;
//here aditional condition
if(a.Country=="Spain") //condition for last item
return 2;
if(a.Country=="Brazil") //condition for always in first item
return -1;
return 0;
}
I am running Person.sort(compare); to do the sort.
b.country == "Spain"andb.country == "Brazil"as wellPerson.reduce(function (o, current) {o[current.Country] = (o[current.Country] || []).concat(current.Name); return o}, {}).