Huw Davies
Huw Davies

Reputation: 811

Understanding a Javascript Codewars challenge

     var gimme = function (inputArray) {
     var order = inputArray.slice().sort(function(a,b) { return a-b;});
    return inputArray.indexOf(order[1]);
     };

This is a function to find the index number of the middle number in a sequence, when given a triplet of numbers. However I don't understand the section:

     (function(a,b) { return a-b;});

Could someone explain the purpose of this part? I would be very grateful. Thanks!

Upvotes: 3

Views: 347

Answers (1)

meskobalazs
meskobalazs

Reputation: 16031

This is an example from MDN:

var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
    return a - b;
});
console.log(numbers);

The result is [1, 2, 3, 4, 5];

So this is a very simple comparator for integers.


Comparators works like the following:

  • if a < b, return a negative
  • if b < a, return a positive
  • in other cases, return zero

This function uses a simple mathematical property of integers.

Upvotes: 3

Related Questions