JavaScript之数据去重复的方法【先排序再递归方法总结】

其他方法参考: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));

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值