排序在Javascript [&QUOT数组; $ 85 QUOT;," 88美元"," $ 9.35"," $ 95 QUOT;," 96"," 126"," 5.95"," $ 36英寸;,"€124 QUOT;] [英] Sorting an Array in Javascript ["$85", "88 dollars", "$9.35", "$95", "96", "126", "5.95", "$36", "€124"]

查看:106
本文介绍了排序在Javascript [&QUOT数组; $ 85 QUOT;," 88美元"," $ 9.35"," $ 95 QUOT;," 96"," 126"," 5.95"," $ 36英寸;,"€124 QUOT;]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的数组,我想重新排序。此数组可能包含只是数字,或者只是文字,或描述货币时的组合等。下面code精美的作品,如果它要么单词或只是数字,但不下令货币人类所期望的方式。它下令货币字典序($ 100是前$ 3),而我想用忽略了其他任何贵重的字符数来订购吧。

I've got a simple array that I'd like to reorder. This array could contain just numbers, or just words, or a combination like when describing currency. The following code works beautifully if it's either words or just numbers but doesn't order the currency the way a human would expect. It orders currency lexicographically ($100 is before $3), whereas I'd like to order it by number ignoring any other characters in the value.

howmuchdata = ["$85", "88 dollars", "$9.35", "$95", "96", "126", "5.95", "$36", "€124"];
howmuchdata = howmuchdata.sort();
howmuchdata = howmuchdata.sort(function(a,b){return a-b});
console.log(howmuchdata);

难道只是删除一切,但数量的问题排序的基础上留下的号码,加在辗转其他任何回来吗?无论被删除,放回可能是每个值也是不同的,所以我不能只毯子把它拿出来,并把它放回去,它必须在每个值的基础上完成。我想数组也返回:

Is it just a matter of removing everything but the number, sorting based on the number left behind and adding whatever else was removed back in? Whatever is removed and put back may be different for each value too, so I can't just blanket take it out and put it back, it has to be done on a per value basis. I'd like the array returned as such:

howmuchdata = ["5.95", "$9.35", "$36", "$85", "88 dollars", "$95", "96", "€124", "126"];

非常感谢您的帮助!

Thanks very much for your help!

推荐答案

您可以在排序回调使用正则表达式,就像这样:

you can use RegEx in the sorting callback, just like that:

howmuchdata = ["$85", "88 dollars", "$9.35", "$95", "96", "126", "5.95", "$36", "€124"];
howmuchdata = howmuchdata.sort();
howmuchdata = howmuchdata.sort(function(a,b){
    a = parseFloat(a.replace(/[^\d\.]/,''));
    b = parseFloat(b.replace(/[^\d\.]/,''));

    return a-b;
});
console.log(howmuchdata);

祝你好运!

这篇关于排序在Javascript [&QUOT数组; $ 85 QUOT;," 88美元"," $ 9.35"," $ 95 QUOT;," 96"," 126"," 5.95"," $ 36英寸;,"€124 QUOT;]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆