JavaScript sorting using function -


while doing online course came across following code. unable understand logic of method. grateful if can me understand code:

var v=[30,2,1,9,15,10,55,20,45,30,25,40,50,35]; var msg = document.getelementbyid("message") msg.innerhtml +="<p><strong>original order:</strong>[" + v + "]<p>";  v.sort(); msg.innerhtml +="<p><strong>after sorting order(string):</strong>[" + v + "]<p>";  v.sort(function(a,b){return a-b;}); msg.innerhtml +="<p><strong>after sorting order(ascending):</strong>[" + v + "]<p>";  v.sort(function(a,b){return b-a;}); msg.innerhtml +="<p><strong>after sorting order(descending):</strong>[" + v + "]<p>"; 

i need understand function(a,b){return a-b} - how function helping javascript sorting? please note new programming.

although others have provided many great links wanted share 1 way think basic of sort functions.

imagine have basic array:

var test = [1, 10];

the sort function accepts function parameter signature:

function (firstval, secondval) {    return number; } 

when apply sort test array

test.sort(function(firstval, secondval) {    // firstval = 1   // secondval = 10    // notes:   // return negative_number if firstval should come *before* secondval   // return 0 if firstval equals secondval   // return positive_number if firstval should come *after* secondval    // return firstval - secondval;  // -9; 1 come before 10; [1, 10]   return secondval - firstval; // 9; 10 come before 1; [10, 1]; }); 

that function ran on values in array. if think 2 value find easier reason sort method. javascript handle algorithm , believe of links mentioned cover how accomplishes that.


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -