0

While doing an online course I came across the following code. I am unable to understand the logic of this method. I will be grateful if someone can help me understand the 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 to understand function(a,b){return a-b} - how is this function helping JavaScript sorting? Please note I am new to programming.

1

2 Answers 2

2

Although others have provided many great links I wanted to share one way I think about the most basic of sort functions.

Imagine you have a very basic array:

var test = [1, 10];

The sort function accepts a function as a parameter with the signature:

function (firstVal, secondVal) { 
  return NUMBER;
}

When you apply sort to the 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 will come before 10; [1, 10]
  return secondVal - firstVal; // 9; 10 will come before 1; [10, 1];
});

That function will then be ran over all the values in the array. But if you only think about 2 value I find it much easier to reason about the sort method. Javascript will handle the algorithm for you and I believe some of the links mentioned will cover how it accomplishes that.

Sign up to request clarification or add additional context in comments.

Comments

0

The JavaScript sort function takes the returned value of the function (that is the parameter of the sort function) to decide how to move the array round a is a value in the array b is a value right next to it. If a negative number is returned it moves b in front of a if a positive number is returned it moves a in front of b if 0 is returned they stay where they are. This is run over and over for every value in the array until the array no longer changes. As others have said a more detailed description can be found on the Mozilla site

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.