1

I was searching for "how to sort multiple arrays at once" and found this question here:
Sorting multiple arrays at once
And there a nice answer from Alexander solving my problem. But I don't fully understand this part from the answer right there:

/* A shorthand function */
var comparator = function(arr) {
    return function(a, b) {
        return ((arr[a] < arr[b]) ? -1 : ((arr[a] > arr[b]) ? 1 : 0));
    };
};

Could someone explain me what this part of his code does?

Community
  • 1
  • 1
TheWandererr
  • 454
  • 5
  • 29
  • 1
    It's comparing values in the array passed in and returning a -1 if the next element is great than the current and a 1 if the current is greater than the next, otherwise returns a 0 if their equal. – jordaniac89 Sep 20 '16 at 14:45
  • 1
    Also, look up ternary operators for the syntax for the last return statement. – jordaniac89 Sep 20 '16 at 14:46
  • 1
    It takes an array and returns a function, when invoked by two index arguments you get a comparison value of the items at those indices. – Redu Sep 20 '16 at 14:47

2 Answers2

1

It is sorting an array of indices by the respective values in arr. To be exact, comparator takes an array and returns a closure function that can be used to compare two index numbers with each other, by looking up the values at these indices in the arr and comparing them.

Bergi
  • 513,640
  • 108
  • 821
  • 1,164
1

This function will compare the values of 2 indexes of an array. The return uses a syntax called Conditional Operator. Here is a nice link that explains it.

Question Mark in JavaScript

Community
  • 1
  • 1
Sari Rahal
  • 1,603
  • 25
  • 44