How to Perform Case-insensitive Sorting of Array in JavaScript
In this tutorial, you will learn how to perform case-insensitive sorting of array in javascript. Case-sensitive sorting can be easily achieved using sort()
and reverse()
methods in javascript, but for case-insensitive sorting, you need to do a little extra work.
There are numerous ways to perform case-insensitive sorting and here, I am going to share one of my approaches in solving such a problem. As you know sort()
method can take a compare function as a parameter and that function should return positive, negative, or 0 integer to decide sort order.
To accomplish our goal, we need to work on a custom compare function that takes 2 items from the array for comparison at a time. Inside this compare function, we are going to use localeCompare()
and toLowerCase()
methods.
The localeCompare()
method is responsible for comparison and it returns positive, negative, or 0 integer. The toLowerCase()
method makes sure that the string should be in lowercase before doing the comparison. I would suggest you to read MDN docs to learn about the localeCompare()
method.
In the following example, we will sort an array in ascending or descending order on a button click and display its items on the screen. Please have a look over the code example and the steps given below.
HTML & CSS
- We have 3 elements in the HTML file (
div
,button
, andul
). Thediv
element is just a wrapper for the rest of the elements. - The first
button
element has“Ascending”
and the secondbutton
element has“Descending”
asinnerText
. - The
ul
element is empty for now since we will populate it dynamically using javascript. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div> <button id="btnAsc">Ascending</button> <button id="btnDesc">Descending</button> <ul></ul> </div> <script src="script.js"></script> </body> </html>
div { width: 15%; margin: auto; } button { padding: 10px; } li { font-size: 20px; font-weight: bold; margin-left: -30px; list-style: none; }
Javascript
- We have a global variable
users
and it holds an array of strings. - We have the
addUsers()
method which is responsible for populating theul
element. - In the
addUsers()
method, we are simply looping through theusers
array and creating a template string with a bunch ofli
elements. - We are displaying that list in the
ul
element. - We have selected both the
button
elements by their ids using thedocument.querySelector()
method and stored them inbtnAsc
andbtnDesc
variables respectively. - We have attached the
click
event listener to both thebutton
elements. - In the event handler function of the ascending button, we are calling the
sort()
method and passing a custom compare function to it. Inside compare function, we are changing the case of both the items to lower usingtoLowerCase()
method and doing comparison usinglocaleCompare()
method. Later, we are updating the list of users by calling theaddUsers()
method. - In the event handler function of the descending button, we are doing everything the same as we were doing for the ascending order, but we are also calling the
reverse()
method to change the order to descending.
let users = ['Peter', 'Marks', 'cathy', 'James', 'Sam']; function addUsers(){ let template = users.map(user => `<li>${user}</li>`).join('\n'); document.querySelector('ul').innerHTML = template; } addUsers(); let btnAsc = document.querySelector('#btnAsc'); let btnDesc = document.querySelector('#btnDesc'); btnAsc.addEventListener('click', () => { users.sort((a,b) => a.toLowerCase().localeCompare(b.toLowerCase())); addUsers(); }); btnDesc.addEventListener('click', () => { users.sort((a,b) => a.toLowerCase().localeCompare(b.toLowerCase())); users.reverse(); addUsers(); });