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?

3
  • 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. Commented Sep 20, 2016 at 14:45
  • 1
    Also, look up ternary operators for the syntax for the last return statement. Commented Sep 20, 2016 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. Commented Sep 20, 2016 at 14:47

2 Answers 2

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

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

Comments

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.

Comments

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.