如何在 JavaScript 中对美元数字范围进行排序



我正在尝试在JavaScript中对美元范围进行排序。问题是响应值是这样排序

['$10,000 - $29,999', '$30,000 - $49,999', '$5,000 - $9,999', '$50,000+', 'Lower than $5,000']
needs to be sorted to
['Lower than $5,000', '$5,000 -$9,999', '$10,000 - $29,999', '$30,000 - $49,999', '$50,000+']

我想像这样按升序排序,但我也希望它在某种意义上是健壮的,如果 API 更改了它发送此数据的顺序,它仍然保持相同的排序:

有没有办法在不对排序算法进行硬编码的情况下做到这一点?

好吧,你可以试试这个:

    let r = ['$10,000 - $29,999', '$30,000 - $49,999', '$5,000 - $9,999', '$50,000+', 'Lower than $5,000'];
    r.sort((a, b) => {
      return parseInt(a.match(/$d+,d+/gi).pop().replace(/D/gi, ""), 10) - parseInt(b.match(/$d+,d+/gi).pop().replace(/D/gi, ""), 10);
    });
    console.log(r);

解释

  1. 删除每个不是数字的字符
  2. 将其解析为一个数字
  3. 比较一下

编辑

我已经编辑了我的代码以响应评论(我知道这不是最漂亮的代码,但它有效(

如果ranges将保留在时间上,则可以创建一个对象来维护ranges和指定顺序之间的关系。稍后您可以在 Array.sort(( 方法中使用此对象:

const rangeOrder = {
  'Lower than $5,000': 0,
  '$5,000 - $9,999': 1,
  '$10,000 - $29,999': 2,
  '$30,000 - $49,999': 3,
  '$50,000+': 4,  
}
let input =  ['$10,000 - $29,999', '$30,000 - $49,999', '$5,000 - $9,999', '$50,000+', 'Lower than $5,000'];
console.log(input.sort(
  (a, b) => rangeOrder[a] - rangeOrder[b]
));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

另一种解决方案是避免对范围进行编码,可以使用自定义函数来匹配每个字符串上的最大范围值。

let input =  ['$10,000 - $29,999', '$30,000 - $49,999', '$5,000 - $9,999', '$50,000+', 'Lower than $5,000'];
const matchValue = (str) =>
{
    let matches = str.match(/d+,d+/g);
    let maxVal = matches.length > 1 ? matches[1] : matches[0];
    return +(maxVal.replace(",", ""));
}
input.sort((a, b) => matchValue(a) - matchValue(b));
console.log(input);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

最新更新