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.
Firstly you need to check b
against those strings as well, and second of all, your special comparisons need to come before the general ones.
Working Live Demo:
function compare(a, b) { if (a.Country == "Spain") return 1; if (a.Country == "Brazil") return -1; if (b.Country == "Spain") return -1; if (b.Country == "Brazil") return 1; if (a.Country < b.Country) return -1; if (a.Country > b.Country) return 1; return 0; } var Person = [{ "Country": "Japan", "Name": "user1" }, { "Country": "Spain", "Name": "user24" }, { "Country": "Usa", "Name": "user1" }, { "Country": "Brazil", "Name": "user1" }]; Person.sort(compare); console.log(Person);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.