如何使用格式" Rs将价格作为字符串对集合进行排序。 350,40"

时间:2015-01-14 09:05:39

标签: javascript jquery

我有一个Javascript数组,对象包含price作为字符串,格式如下:

results:[{
image: "http://dummyhost/new3305-82-thumb.jpg",
product_title: "Nokia Lumia 1540",
price: "Rs. 50,790"
},
{
image: "http://dummyhost/new3305-82-thumb.jpg",
product_title: "Nokia Lumia 1520",
price: "Rs. 37,790"
}]

我知道我们可以使用以下函数原型来使用string或interger对值进行排序:

Array.prototype.sortByProp = function(p){
 return this.sort(function(a,b){
  return (a[p] > b[p]) ? 1 : (a[p] < b[p]) ? -1 : 0;
 });
}

我希望对字符串和整数的组合进行排序,我们会根据国家/地区货币格式获得api响应。

3 个答案:

答案 0 :(得分:2)

您可以将"Rs. 50,790"格式的价格转换为数字,如下所示:

p = "Rs. 50,790";
p = +p.replace(/\D/g,"");

也就是说,执行正则表达式替换以删除字符串中的所有非数字(假设逗号是注释中提到的千位分隔符),然后使用一元加运算符将结果字符串转换为数字

然后您可以使用数值进行排序。我不确定您希望如何将其纳入您的通用sortByProp()功能中。也许通过添加一个标志来告诉它将属性转换为数字:

Array.prototype.sortByProp = function(p,isNumeric){
  return this.sort(function(a,b){
    a = isNumeric ? +a[p].replace(/\D/g,"") : a[p];
    b = isNumeric ? +b[p].replace(/\D/g,"") : b[p];

    return (a > b) ? 1 : (a < b) ? -1 : 0;
  });
};

results.sortByProp("price", true);
// or for other fields omit the second parameter or pass in false:
results.sortByProp("product_title");

答案 1 :(得分:1)

您必须使用排序方法解析价格

myArray.sort(function(a, b){
    var pA = parseFloat(a["price"].substr(4).replace(",", ""));
    var pB = parseFloat(b["price"].substr(4).replace(",", ""));

    if (pA < pB) return -1;
    if (pA > pB) return 1;
    return 0;
});

编辑:点的好点

答案 2 :(得分:0)

这个怎么样:

Array.prototype.sortByProp = function(p){
    return this.sort(function(a,b){
        console.log(a,b)
        return (parseInt(a['price'].substring(4).replace(',','')) >   parseInt(b['price'].substring(4).replace(',',''))) ? 1 : 0;
     });
}

它需要一个以位置2开头的子字符串,然后将,替换为空。 parseInt(a['price'].substring(4).replace(',',''))