Sort Array of Strings in JavaScript

PaperInFlames
2 min readMar 15, 2023

Here I’m sharing three ways to sort an array of strings in JS.

Array of leaves

Approach 1:

We can directly use the inbuilt methods of array objects in JS. If we want to sort in ascending order we can simply use the Sort method and Reverse method for descending order.

For example, here I have an array of strings which is a combination of both text and numbers.

// Sort in ascending order

let arr = ['K38', 'K23', 'K89'];
console.log(arr.sort())
//Output : ["K23", "K38", "K89"]

// Sort in descending order

let arr = ['K38', 'K23', 'K89'];
console.log(arr.reverse())
//Output : ["K89", "K23", "K38"]

Approach 2:

Another way is using the inbuilt methods of a string in JS. Here we have to swap the values for ascending or descending orders. In the below example, we have to swap a and b.

// Sort in ascending order

let arr = ['K38', 'K23', 'K89'];
let res= arr.sort((a,b) => a.localeCompare(b));
console.log(res)
//Output : ["K23", "K38", "K89"]

// Sort in descending order

let arr = ['K38', 'K23', 'K89'];
let res= arr.sort((a,b) => b.localeCompare(a));
console.log(res)
//Output : ["K89", "K23", "K38"]

Approach 3:

Another way is by using conditions inside the sort method. Usually, we can use the below method to sort the numbers or values of an object.

// Sort in ascending order

let numArr = [92,45,14,21,93,43]
let numRes = numArr.sort((a,b) => a-b)
console.log(numRes)
//Output : [14, 21, 43, 45, 92, 93]

// Sort in descending order

let numArr = [92,45,14,21,93,43]
let numRes = numArr.sort((a,b) => b-a)
console.log(numRes)
//Output : [93, 92, 45, 43, 21, 14]

Whereas, here this approach doesn’t work. So we have to follow the below approach.

// Sort in ascending order

let arr = ['K38', 'K23', 'K89'];
let res = arr.sort((a,b) => (a < b ? -1 : a > b ? 1 : 0));
console.log(res)
//Output : ["K23", "K38", "K89"]

// Sort in descending order

let arr = ['K38', 'K23', 'K89'];
let res = arr.sort((a,b) => (a > b ? -1 : a < b ? 1 : 0));
console.log(res)
//Output : ["K89", "K23", "K38"]

Hope this helps 😀🫠

--

--