Home Communities
IT Knowledge
Inspiration
Languages
EN

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

6 points
Created by:
748

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

Presented comparison result we should understand the following way:

• `-1` when first value is smaller than second one,
• `0` when values are equal,
• `+1` when first value is greater than second one.

Quick solution:

``````// ONLINE-RUNNER:browser;

const compareValues = (a, b) => {
if (a < b) return -1;
if (a > b) return +1;
return 0;
};

// Usage example:

console.log(compareValues(2, 1));  // +1``````

Note: the presented function compares in correct way ISO 8601 string dates also.

## Practical example

``````// ONLINE-RUNNER:browser;

const compareValues = (a, b) => {
if (a < b) return -1;
if (a > b) return +1;
return 0;
};

// Usage example:

// Booleans:
console.log(compareValues(true, true));   //  0   // true is equal to true
console.log(compareValues(true, false));  // +1   // false is before true (because 0 means false, other values mean true)
console.log(compareValues(false, true));  // -1   // true is after false  (because 0 means false, other values mean true)

// Numbers:
console.log(compareValues(1, 1));   //  0   // 1 is equal to 1
console.log(compareValues(2, 1));   // +1   // 2 is after 1
console.log(compareValues(1, 2));   // -1   // 1 is before 2

// Strings:
console.log(compareValues('aaa', 'aaa'));  //  0   // 'aaa' is equal to 'aaa'
console.log(compareValues('aab', 'aaa'));  // +1   // 'aab' is after 'aaa'
console.log(compareValues('aaa', 'aab'));  // -1   // 'aaa' is before 'aab'

// Dates:
console.log(compareValues(new Date(2023, 1, 1), new Date(2023, 1, 1)));  // 0    // 2023-01-01 is equal to 2023-01-01
console.log(compareValues(new Date(2023, 1, 2), new Date(2023, 1, 1)));  // +1   // 2023-01-02 is after 2023-01-01
console.log(compareValues(new Date(2023, 1, 1), new Date(2023, 1, 2)));  // -1   // 2023-01-01 is before 2023-01-02``````

## Sort array example

``````// ONLINE-RUNNER:browser;

const compareValues = (a, b) => {
if (a < b) return -1;
if (a > b) return +1;
return 0;
};

// Usage example:

const booleans = [true, false, true];
const numbers = [1, 3, 2];
const strings = ['aaa', 'aac', 'aab'];
const dates = [new Date(2023, 1, 1), new Date(2023, 1, 3), new Date(2023, 1, 2)];

booleans.sort(compareValues);
numbers.sort(compareValues);
strings.sort(compareValues);
dates.sort(compareValues);

console.log(booleans);  // false, true, true
console.log(numbers);   // 1, 2, 3
console.log(strings);   // aaa, aab, aac
console.log(dates.map(date => date.toISOString().substring(0, 10)));  // 2023-01-31, 2023-02-01, 2023-02-02``````

## Alternative titles

Join to our subscribers to be up to date with content, news and offers.