+ 2

Could anyone pls demonstrate the below example how the .sort() does the comparison?

let a=[3,2,5] console.log(a.sort(function(a, b){return a-b})); I have read few stuff from internet but it would be good if anyone could explain the above code with the array 'a'.

3rd Jan 2023, 5:58 PM
Levi
Levi - avatar
1 Odpowiedź
+ 2
I recommend to read the ultimate source of truth: the MDN documentation. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort If the sort function has an argument, this argument is a comparator function that takes two values, and must return a number. This function determines the ordering of whatever is found in the array. Remember that an array may contain other things not just numbers, like strings or any is object. So in terms of this comparator function, it takes two arguments a and b, which represent any two values during the process of sorting. If the result of this function is greater than zero, then a is going to be sorted after b, and vice versa. What you have in your example, actually has the same effect as the default sorting (ascending).
3rd Jan 2023, 6:48 PM
Tibor Santa
Tibor Santa - avatar