Javascript排序具有首选项的字符串数组

时间:2015-08-28 00:37:09

标签: javascript arrays sorting

我正在尝试在JavaScript中对数组进行排序,但我希望一个特定项目始终位于排序中,而另一个特定项目始终是最后一个:

var Person= [{
   "Country": "Japan",
   "Name": "user1"

}, {
   "Country": "Spain",
   "Name": "user24"

}, {
   "Country": "Usa",
   "Name": "user1"

}, {
   "Country": "Brazil",
   "Name": "user1"

}];

这是我的compare功能:

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;
    }

我正在运行Person.sort(compare);来进行排序。

1 个答案:

答案 0 :(得分:3)

首先,你需要检查b对这些字符串,其次,你的特殊比较需要先于普通字符串。

现场演示:

&#13;
&#13;
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);
&#13;
&#13;
&#13;