Brainlet here

can someone explain to me how this works?
myArr = ["JANE", "ADAM", "AARON", "BETTY", "YUSEF"];

myArr.sort(function(a, b){
if (a < b) {return -1};
if (a > b) {return 1};
});

//myArr is now sorted in alphabetical order

Attached: 1482457460067.jpg (412x985, 270K)

Other urls found in this thread:

youtube.com/watch?v=kPRA0W1kECg
twitter.com/NSFWRedditImage

BRRRRRRAAAAAAAAAAAAAAAAAAAP

Attached: 1528320983591.jpg (342x311, 19K)

What about it confuses you, friend? Which parts do you understand?

if only we had a thread for questions like this

friend
why is words higher in the alphabet < words lower in the alphabet true
what's the difference between returning 1 and negative 1
how does that sort an entire array, if it's comparing each element.
why does
myArr.sort(function(a,b){ return a < b; });

not just work

1. Javascript compares strings by their alphabetical index.
2. The sort array prototype optionally takes a sorting function as an argument.
3. This function returns +1 if the value should be shifted left, -1 for right.
4. Technically you should allow for duplicate values and return 0 if an exact match is found.

myArr.sort((a, b) => {
return a < b ? -1 : a > b ? 1 : 0;
});

In JavaScript, string < string does a lexicographical (alphabetical) comparison.

The function passed to .sort should return -1, 0 and 1 depending on whether a comes before, is equal to, or comes after b.

There's no reason why it couldn't have worked the way you describe it, but then if the sorting algorithm cared about less-or-equal vs merely less, it would have to call your function twice which would be slower.

it works fine
["JANE", "ADAM", "AARON", "BETTY", "YUSEF"].sort(function(a, b){
return a > b;
});

it's called a sort delegate ... tf

thanks bros it makes more sense now. What do 'a' and 'b' actually represent though? i thought it was going through the array, comparing 'a' each element to 'b' the element after it. Is that correct?