#Sorting numerical values in an array.

11 messages · Page 1 of 1 (latest)

fluid karma
#

Could anybody explain why sorting numerical values in an array needs a callback function? And what format should it be?

drifting flume
#

Needs a callback?

fluid karma
#

Apparently, that's what this guide im following is claiming

#

Callback function as in

#
const number = [1,4,6,2,3];
const numberSorted = number.sort(function (a, b){
  return a-b;
});
#

Why is a-b needed here, what does it represent?

drifting flume
#

The sort function decides which number is smaller by checking if the value returned is negative, positive, or 0.

#

If a is larger than b then the return will be positive. If a is smaller than be the return will be negative. If they're equal the return will be 0.

fluid karma
#

I see, so a and b represent 2 elements of the array?

drifting flume
#

Yep

fluid karma
#

Aight, thanks