1

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.

3
  • 1
    You need to check for the condition when b.country == "Spain" and b.country == "Brazil" as well Commented Aug 28, 2015 at 0:39
  • …and you need to check for those conditions before the normal comparisons. Commented Aug 28, 2015 at 0:43
  • Why don't you just group by country? Person.reduce(function (o, current) {o[current.Country] = (o[current.Country] || []).concat(current.Name); return o}, {}). Commented Aug 28, 2015 at 0:43

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

thanks "the order of the factors does alter the result" :)
Hi @jearca, do you feel as if I answered your question completely? If so, please don’t forget to mark my answer as "accepted" by clicking the gray checkmark to the left. If your question hasn't been fully answered, please elaborate on what else you need to know so the community can provide you with further help! Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.