Intl.Collator descending order sort

Viewed 2162

Given this example:

let a = ['New York', 'New Hampshire', 'Maryland'];
let collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
a.sort(collator.compare);

How might this array be sorted in descending order?

2 Answers

You can switch the parameters:

a.sort( (x, y) => collator.compare(y, x) )

or sort and reverse:

a.sort(collator.compare).reverse()

The simplest way is to use reverse:

let a = ['New York', 'New Hampshire', 'Maryland'];
a.reverse();

console.log(a)

Or you can loop through a array and unshift each item to new array:

let a = ['New York', 'New Hampshire', 'Maryland'];
let b = [];
a.forEach((item) => {
  b.unshift(item);
})

console.log(b)

Related