js价格排序实现
数组排序(升序/降序)
使用 Array.prototype.sort() 方法对数字数组进行排序。默认情况下,sort() 会将元素转换为字符串并按 Unicode 码点排序,因此需要自定义比较函数。
升序排序:
const prices = [99, 29, 159, 199, 49];
prices.sort((a, b) => a - b);
// 结果: [29, 49, 99, 159, 199]
降序排序:
prices.sort((a, b) => b - a);
// 结果: [199, 159, 99, 49, 29]
对象数组按价格排序
对包含价格属性的对象数组排序时,需在比较函数中指定属性名。

升序:
const products = [
{ name: 'Laptop', price: 999 },
{ name: 'Mouse', price: 49 },
{ name: 'Keyboard', price: 79 }
];
products.sort((a, b) => a.price - b.price);
降序:
products.sort((a, b) => b.price - a.price);
处理浮点数精度
当价格包含小数时,直接相减可能导致精度问题。建议使用 toFixed() 转换后再比较:

const floatPrices = [10.99, 2.50, 5.01];
floatPrices.sort((a, b) => parseFloat(a.toFixed(2)) - parseFloat(b.toFixed(2)));
带货币符号的字符串排序
若价格为字符串形式(如 "$29.99"),需先提取数值部分:
const currencyPrices = ["$29.99", "$9.99", "$199.99"];
currencyPrices.sort((a, b) =>
parseFloat(a.replace(/[^0-9.]/g, '')) -
parseFloat(b.replace(/[^0-9.]/g, ''))
);
多条件排序
当价格相同时,可添加次要排序条件(如按名称字母序):
products.sort((a, b) => {
if (a.price === b.price) {
return a.name.localeCompare(b.name);
}
return a.price - b.price;
});
性能优化
对大规模数据排序时,考虑使用 TypedArray 提高性能:
const largeArray = new Float64Array([99.5, 23.1, 42.8]);
largeArray.sort((a, b) => a - b);






