Where do I Belong: got it but don't completely understand anonymous function

Tell us what’s happening:

I implemented this based on MZ sort(). It is a valid solution, but I don’t get the anonymous function taken as a sort argument: what’s the point of substracting one number from other over and over again. I already saw it in a debugger and what I saw was that if there was a positive result a and b were sorted, otherwise (negative number as result) nothing is sorted and the function goes on…
MZ explains the function in this way: " To compare numbers instead of strings, the compare function can simply subtract b from a . The following function will sort the array in ascending order (if it doesn’t contain Infinity and NaN ):".

Your code so far


function getIndexToIns(arr, num) {
  let numIndex;
  arr.push(num);
  arr.sort(function(a, b){
    return a - b;
  })
  numIndex = arr.indexOf(num);
  
  return numIndex;
}

getIndexToIns([5, 3, 20, 3], 5);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36 OPR/63.0.3368.94.

Link to the challenge:

If compareFunction is supplied, all non- undefined array elements are sorted according to the return value of the compare function (all undefined elements are sorted to the end of the array, with no call to compareFunction ). If a and b are two elements being compared, then:

  • If compareFunction(a, b) is less than 0, sort a to an index lower than b (i.e. a comes first).
  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behavior, thus, not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
  • If compareFunction(a, b) is greater than 0, sort b to an index lower than a (i.e. b comes first).
1 Like

Thank you Ariel. I read that but I’m an amateur!