如何使用符号对数组进行排序?

时间:2012-06-01 20:55:44

标签: javascript arrays

我有一个像这样的数组,带有小数值

["$79.34", "$99.23", "$149", "$139.34", "$379", "$199.00", "$5", "$9", "$14", "$39", "$59", "$24", "$29", "$189", "$10,$20", "$500", "$1", "$4", "$8.66", "$2", "$19", "$18", "$11", "$15", "$40", "$89", "$100", "$400.15", "$30,$119", "$15,$30"]

对于我的商店,我无法弄清楚如何使用javascript对它们进行排序? $(或任何符号)似乎对我造成了问题?

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

var prices = [...]
prices.sort(function(a,b) { return (a.substring(1)) - (b.substring(1)); })

会做到这一点。

答案 1 :(得分:0)

编辑:我写了JSFiddle to demonstrate this

function sortPrices(priceStrings) 
{
    //first sanitize the data
    for (var i = 0; i < priceStrings.length; i++) 
    {
        if (priceStrings[i].toString().search(",") != -1) 
        {
            var splits = priceStrings[i].toString().split(",");
            priceStrings.splice(i, 1)
            priceStrings = priceStrings.concat(splits);
            i--;
        }
    }
    var prices = [];
    for (var i = 0; i < priceStrings.length; i++) 
    {
        priceStrings[i] = priceStrings[i].toString().replace("$", "");
        prices.push(parseFloat(priceStrings[i]));
    }

    prices.sort(function(a,b){return a - b});

    return prices;
}​