AmirWG
0
Q:

sorting array from highest to lowest javascript

// Sort an array of numbers 
let numbers = [5, 13, 1, 44, 32, 15, 500]

// Lowest to highest
let lowestToHighest = numbers.sort((a, b) => a - b);
//Output: [1,5,13,15,32,44,500]

//Highest to lowest
let highestToLowest = numbers.sort((a, b) => b-a);
//Output: [500,44,32,15,13,5,1]
6
// Sort an array of numbers based on numerical value.
let numbers = [23, 65, 88, 12, 45, 99, 2000]

let sortednumbers = numbers.sort((a, b) => a - b);
//=> [12, 23, 45, 65, 88, 99, 2000]
0
By default, the sort() method sorts the values as strings in alphabetical and ascending order.
This works well for strings ("Apple" comes before "Banana"). However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".
Because of this, the sort() method will produce an incorrect result when sorting numbers.
You can fix this by providing a "compare function"

numbers = [2, 3, 41, 3, 2, 4, 5];

numbers.sort(function(a,b){return a-b});

// For more info on the compare function see https://www.w3schools.com/jsref/jsref_sort.asp
11
function myFunction() {
  points.sort(function(a, b){return a-b});
  document.getElementById("demo").innerHTML = points;
}
0

New to Communities?

Join the community