3
     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!

1 Answer 1

3

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.

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

3 Comments

Thanks so much! What do you mean when you say comparator?
A Comparator is an object which compares other objects and decides whether one is "larger" or they are equal. For example the <= operator, is a partial sort comparator on the set of real numbers.
Very helpful. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.