Click here for v1.x documentation.
Dinero.js
Dinero.js version

compare

number

Compare the value of a Dinero object relative to another. This is useful for sorting Dinero objects.

Possible return values are:

  • -1 if the first Dinero object is less than the other
  • 1 if the first Dinero object is greater than the other
  • 0 if both objects are equal

You can only compare objects that share the same currency. The function also normalizes objects to the same scale (the highest) before comparing them.

Copy linkParameters

NameTypeDescriptionRequired
dineroObjectDinero<TAmount>

The first Dinero object to compare.

Yes
comparatorDinero<TAmount>

The second Dinero object to compare.

Yes

Copy linkCode examples

Copy linkCompare two objects

import { dinero, compare } from 'dinero.js';
import { USD } from '@dinero.js/currencies';

const d1 = dinero({ amount: 800, currency: USD });
const d2 = dinero({ amount: 500, currency: USD });

compare(d1, d2); // 1

Copy linkCompare two objects after normalization

import { dinero, compare } from 'dinero.js';
import { USD } from '@dinero.js/currencies';

const d1 = dinero({ amount: 5000, currency: USD, scale: 3 });
const d2 = dinero({ amount: 800, currency: USD });

compare(d1, d2); // -1

const d3 = dinero({ amount: 5000, currency: USD, scale: 3 });
const d4 = dinero({ amount: 500, currency: USD });

compare(d3, d4); // 0

Copy linkSort arrays of objects

One of the main use cases of the compare function is to sort Dinero objects. For example, you can use it with Array.prototype.sort.

import { dinero, compare } from 'dinero.js';
import { USD } from '@dinero.js/currencies';

const d1 = dinero({ amount: 900, currency: USD });
const d2 = dinero({ amount: 500, currency: USD });
const d3 = dinero({ amount: 800, currency: USD });

const lowToHigh = [d1, d2, d3].sort(compare);
const highToLow = [d1, d2, d3].sort((a, b) => compare(b, a));