I can't understand how this .sort() is using that function to give an ascending order of arr array

Tell us what’s happening:
Describe your issue in detail here.
Individually, I know what only .sort() does to an array. It was difficult to solve this challenge so saw the hint to use .sort() & a function inside it, but got stuck on how .sort() uses that function to return an array sorted in ascending order. Would love if you give a detailed explanation as much as possible. :blush::v:
Your code so far

function getIndexToIns(arr, num) {
let sortedArr = arr.sort((a, b) => a - b); // I don't understand how this .sort() is using that function to give an ascending order of arr array.
getIndexToIns([5, 3, 20, 3], 50);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36

Challenge: Where do I Belong

Link to the challenge:

Hi @biswasprasana004, the most detailed explanation you can find about the compare function is probably one the MDN sort documentation page.

But to make it short, the sorting will change based on the returning value:

  • return > 0 sort b before a
  • return < 0 sort a before b
  • return === 0 keep as is

Then it’s up to you to find a criteria in which a can be bigger or smaller than b.
In this case it’s “easy” as they are all numbers, but you may need some additional logic if you want to sort other kind of data :slight_smile:

Hope this helps.

1 Like

So a function used inside sort is expected to return one of three values:

  • less than zero indicates the second should be placed before the first (reverse order),
  • greater than zero indicates that the first should be placed before the second (given order),
  • and zero, which indicates leave them in the given order, but can be useful in special cases.

So, with the function (a, b)=>a-b, we’re returning the value of a minus b. If a is greater, the value will be positive. If b is greater, the value will be negative.

Thus, the sorry function gets the ranges of values it expects.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.