How does "array.Sort()" work?

Asked

Viewed 174 times

0

How does the

array.sort((a, b) => a - b) 

?

Why is this symbol =>, and why this operation a - b Are you subtracting the elements? That doesn’t make sense to me.

  • That => is called Arrow functions https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions.

  • I do not think that the question should remain as pending, the questioning is very clear and the explanation is simple.

  • 1

    About the syntax with => (Arrow functions): What is Arrow Function and when to use? // About the Array.prototype.sort: How the Sort method works?. I closed as too wide because they are two totally different things.

  • @bfavaretto had indicated the sup of the Sort before the first closure I would not have answered, and of course I had not found it ample because it was all part of an explanation of the sort(), although I knew that the => had already answered, the function in itself did not.

  • @Maniero I closed first to search for the links later, because I was sure they existed on the site.

  • And I chose "broad" and not duplicate because I was in doubt if it was a good link two duplicates on different subjects @Maniero.

  • @bfavaretto that’s what else has.

Show 2 more comments

1 answer

2


Part has already been answered in What the operator means "=>"? (or all of these What is Arrow Function and when to use?).

It makes sense. Whenever you use a function you should read its documentation before using. You can not use "in madness", you have to study the tool, know how it works, how is the way to use. See the job documentation. It says there that if the value returned by this function lambda is negative then the element a is smaller than the element b, if the result is 0 then they are equal, and if it is greater than 0 the b is less than a. And knowing which one is the smallest is a basic need to sort a data collection. So you’re moving on to the sort() a function that indicates which of the two elements is the least or equal, so the sorting algorithm will know what to do, but the criterion for deciding this you do as you wish.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.