argfede
argfede

Reputation: 19

How does Return 1 or -1 works/means in array.sort (a>b) (JS)? Asking about process of the methos array.sort

I can't figure out what return 1 or -1 means in array.sort in js.

    const hola = [0, 4, 10, 60, 5]
const holaSorted = hola.sort(function(a,b) {
    if (a>b) {
        return -1;
    } else {
    return 1;
  } 
});
console.log(holaSorted);

console.table(holaSorted);`

[60, 10, 5, 4, 0]

Upvotes: 0

Views: 1418

Answers (1)

Bibberty
Bibberty

Reputation: 4768

First of, as discussed above the MDN Sort description is very good.

But we can simplify for here:

When we call sort it allows us to provide a function to evaluate two elements of the array at any given time.

The function should return:

  • a negative value if a < b
  • a positive value if a > b
  • and 0 if a === b.

The sort function will then use that value to order those two elements respectively.

// Number ordering is very straight forward. 
const hola = [0, 4, 10, 60, 5]
const holaSorted = hola.sort((a,b) => a-b); 
console.log(holaSorted);

// reverse the order.
const holaSorted2 = hola.sort((a,b) => b-a);
console.log(holaSorted);

But not everything is a simple number, often we want to sort objects, this is where it becomes more important to provide a custom evaluator.

Below we sort using name and we need to pass back 1 || -1 || 0 based on a string compare.

const people = [
  {
    name: 'Bob',
    age: 20
  },
  {
    name: 'Anne',
    age: 50,
  },
  {
    name: 'Terry',
    age: 5
  }
];

// Order by name
const byName = people.sort((a,b) => (a.name < b.name) ? -1 : (a.name > b.name) ? 1 : 0);

console.log(byName);

// Order by age
const byAge = people.sort((a, b) => a.age-b.age);

console.log(byAge);

Upvotes: 2

Related Questions