js sort return value code example
Example 1: how to sort an array by value in javascript
//ascending order
arr.sort(function(a, b){return a-b});
arr.sort((a, b) => a - b);
//descending order
arr.sort(function(a, b){return b - a});
arr.sort((a, b) => b - a);
Example 2: why sort() return - 1 js
var arr=[1,2,3,4,5,6,100,999]
arr.sort((a,b)=>{
if (a%2==b%2) return a-b;
if (a%2>b%2) return -1;
return 1;
})
console.log(arr)
//output: [ 1, 3, 5, 999, 2, 4, 6, 100 ]