Languages
[Edit]
EN

JavaScript - compare strings

4 points
Created by:
Root-ssh
178290

In this article, we're going to have a look at how to compare two strings when we want to sort them in JavaScript.

Quick solution:

 

Introduction

Edit

There are two approaches to comparing strings:

  • String localeCompare() method - that returns information which one should be first according to alphabet letters priority.
  • comparators like: <, >== or === - that return only true or false for compared strings,

The second approach requires at least two tests to know about compared string's priority.

In the below examples you can see practical usage.

1. localeCompare() method example

Edit

String localeCompare method returns -1, 0 or +1 value to inform which one should be first according to alphabet letters priority.

 

2. Compare with comparators example

Edit

With this approach, we need to make a few tests to know which one should be first.

2.1. Simple cases example

Edit

2.2. Reusable function example

Edit

In this section, we want to show how to write our own comparison method using operators.

Note: with this approach we are able to compare numbers, strings, dates and booleans without writing additional functions - so it can be easly used to sort data by any column, e.g. in last section with sorting array of objects.

 

4. Sorting array of objects example

Edit

The approach presented in this section is universal - can be used to sort columns of different types. Check the previous section (3. Custom compare method example) to see the simplest example.

 

See also

Edit
  1. JavaScript - universal way to compare values (boolean, number, string, Date, etc.)

Alternative titles

  1. JavaScript - compare strings (e. g. for sorting / ordering)
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - compare strings

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join