Intl.Collat​​or降序排序

时间:2017-09-22 23:39:04

标签: javascript

给出这个例子:

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

该数组如何按降序排序?

2 个答案:

答案 0 :(得分:2)

您可以切换参数:

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

或排序和反转:

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

答案 1 :(得分:0)

最简单的方法是使用reverse

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

console.log(a)

或者您可以将a数组和unshift每个项目循环到新数组:

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

console.log(b)