0

I have a piece of code here which I am finding difficult in understanding the sorting mechanism. I am new to programming, can anyone help me in understanding

function sortNumber(a, b) {
  return a - b;
}

var numArray = [140000, 104, 99];
numArray.sort(sortNumber);
console.log(numArray);
Satpal
  • 132,252
  • 13
  • 159
  • 168
Onera
  • 687
  • 3
  • 14
  • 34
  • internal use of sort of javascript, will be founded by any sort math algorith, in base iterate all items in array an use an function to know if order is DESC or ASC or any, in base the return function as you put – Álvaro Touzón Feb 22 '17 at 12:17
  • 1
    Please refer https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description – mplungjan Feb 22 '17 at 12:18
  • 1
    Have you read the doc? [Array.sort()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) – Satpal Feb 22 '17 at 12:18
  • yes but when you do this => numArray.sort(sortNumber); what are the values passed in sortNumber(a, b) .. what are a and b values taken – Onera Feb 22 '17 at 12:28
  • 1
    If you're looking for an explanation on how/why this works: The parameter for the sort function needs to be a function that takes parameters a and b. It answers the question "is a "bigger" than b?" The function returns one of three things: 1) a negative value, which indicates that **a** is smaller than **b**, 2) 0, which indicates the values are equal 3) a positive value, which indicates that a is bigger than b. The sort function iterates through the list, calls this function for each pair of elements and based on the results, returns a list sorted with the function you defined. – Juuso Feb 22 '17 at 13:43
  • So the pairs will be like (140000, 104) and (104,99) and (99,140000) ?? and computes like you said in your explanation. – Onera Feb 22 '17 at 14:11

0 Answers0