JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to sort an array of strings in descending order in JavaScript?

With the help of the sort() method, you can sort an array of strings. But the sort() method sorts the array in alphabetical order, so to sort in descending order, you have to either call the reverse() method or pass a comparison function to the sort() method.

let arr = ['candy', 'marshmallow', 'nougat', 'lollipop', 'kitkat'];

arr.sort().reverse();
console.log(arr); //["nougat", "marshmallow", "lollipop", "kitkat", "candy"]

arr = ['candy', 'marshmallow', 'nougat', 'lollipop', 'kitkat'];
arr.sort((a, b)=>{
  if(a>b){
    return -1;
  }else{
    return 1;
  }
});
console.log(arr); //["nougat", "marshmallow", "lollipop", "kitkat", "candy"]

Here is the explanation of the code:

1. The sort() method updates the original array, so if you don't want to modify it, create a copy using the ES6 spread operator.

let arr = ['candy', 'marshmallow', 'nougat', 'lollipop', 'kitkat'];
let copiedArr = [...arr];
copiedArr.sort();
console.log(arr); //['candy', 'marshmallow', 'nougat', 'lollipop', 'kitkat']
console.log(copiedArr); //["nougat", "marshmallow", "lollipop", "kitkat", "candy"]

2. Once you have the sorted array elements, you have to call the reverse() method to reverse the order of array elements. In this way, you can sort string array in descending order.

let arr = [1, 2, 3, 4, 5];
arr.reverse();
console.log(arr); //[5, 4, 3, 2, 1]

3. If you don't want to sort the array in alphabetical order, then pass a comparison function to the sort() method. The comparison function accepts two parameters, and depending upon the value returned by the comparison function, array elements are sorted.

  • If the value returned by the comparison function is less than 0, then the first argument comes before the second argument.
  • If the value returned is greater than 0, then the second argument comes before the first argument.
  • If the function returns 0, then both arguments are considered equal.
arr.sort((a, b)=>{
  if(a>b){
    return -1;
  }else{
    return 1;
  }
});

Recommended Posts