在javaScript中按字符串中的百分比对字符串数组进行排序的最佳方法是什么?

问题描述 投票:1回答:2

我有阵列:

["John (50%)", "Michael (10%)", "Amy (20%)", "Susan (100%)"]

而且我需要根据主要%到最小%对该数组进行排序。如果是这样的话我可以使用lodash,但除此之外我只需要使用vanilla JS。

知道什么是最好的方法吗?

最终结果应该是:

["Susan (100%)", "John (50%)", "Amy (20%)", "Michael (10%)"]

提前感谢您对此事的任何启示。

javascript arrays sorting string-parsing
2个回答
3
投票

您可以获取数值并按值的增量降序排序。

var array = ["John (50%)", "Michael (10%)", "Amy (20%)", "Susan (100%)"];

array.sort(function (a, b) {
    function getValue(s) { return s.match(/\d+/) || 0; }
    return getValue(b) - getValue(a);
});

console.log(array);

0
投票

请尝试以下方法:

var data = ["John (50%)", "Michael (10%)", "Amy (20%)", "Susan (100%)"];
var res = data.sort(function(a, b){
  return b.match(/\d+/) -  a.match(/\d+/);
});
console.log(res);
© www.soinside.com 2019 - 2024. All rights reserved.