OneBite.Dev - Coding blog in a bite size

sort items in array by desc in Javascript

Code snippet on how to sort items in array by desc in Javascript

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

This code sorts items from highest to lowest in a given array. The “arr” is the name of the array being sorted. The sort() method then calls a function that compares two items in the array and returns a value based on the comparison. The function uses the logical operator “return b - a” which subtracts the second value from the first, thus inverting the order (sorts from highest to lowest). This comparison is repeated for each item until the array is sorted.

javascript