其他方法参考:https://segmentfault.com/a/1190000016418021
排序+递归的方法个人感觉容易一些,其他方法可以参考上面别人的分享
let array = [{
amount: 2000,
price: 0.03,
}, {
amount: 2000,
price: 0.08,
}, {
amount: 500,
price: 0.03,
}, {
amount: 2000,
price: 0.01,
}, {
amount: 2000,
price: 0.05,
}, {
amount: 2000,
price: 0.06,
}, {
amount: 2000,
price: 0.06,
}, {
amount: 2000,
price: 0.06,
}, {
amount: 2000,
price: 0.06,
}, {
amount: 2000,
price: 0.04,
}, {
amount: 2000,
price: 0.02,
}, {
amount: 2000,
price: 0.03,
}, {
amount: 2000,
price: 0.06,
}, {
amount: 2000,
price: 0.06,
}, {
amount: 2000,
price: 0.08,
}];
function orderToRepeatandAddAmount (orderList) {
// 先把数组去重复【递归之前必须去重复,否则必错】
orderList.sort((objA, objB) => {
return parseFloat(objA.price) - parseFloat(objB.price);
});
// 对数组中的每一项递归【把相邻且相同价格的订单数量叠加后删除index下标的元素】
(function loop (index) {
if (index >= 1) {
if (parseFloat(orderList[index].price) === parseFloat(orderList[index - 1].price)) {
orderList[index - 1].amount = parseFloat(orderList[index - 1].amount) + parseFloat(orderList[index].amount);
orderList.splice(index, 1);
}
loop(index - 1);
}
})(orderList.length - 1);
return orderList;
}
console.log(orderToRepeatandAddAmount(array));