我有一个 Javascript 数组,其中包含价格作为字符串的对象,格式如下:
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"
}]
我知道我们可以利用以下函数原型(prototype)对字符串或整数进行排序:
Array.prototype.sortByProp = function(p){
return this.sort(function(a,b){
return (a[p] > b[p]) ? 1 : (a[p] < b[p]) ? -1 : 0;
});
}
我希望对字符串和整数的组合进行排序,我们可以得到 api 响应以及特定于国家/地区货币格式的价格。
最佳答案
您可以将“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");
关于javascript - 如何对价格为格式为 "Rs. 350,40"的字符串的集合进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27939142/