JS数组对象的去重和排序操作

最近看到一个比较有趣的问题,记录一下自己的解决方法。

具体代码如下:

/*
* 合并相同价格(price)的数量(amount)并以价格从小到大排序
*/
var dataList = [
    { id: 1, price: 5.5, amount: 3 },
    { id: 2, price: 1.5, amount: 5 },
    { id: 3, price: 3.5, amount: 8 },
    { id: 4, price: 5.5, amount: 2 },
    { id: 5, price: 0.5, amount: 7 },
    { id: 6, price: 1.5, amount: 4 },
    { id: 7, price: 6.5, amount: 9 }
]
// 排序方法
function compare(prop) {
    return function(a, b) {
        return a[prop] - b[prop]
    }
}
dataList.sort(compare('price'))
// 最终的数据
var newArray = []
// 空对象
var newObject = {}
// 重复的数据
var otherArray = []
// 利用对象访问属性的方法,判断对象中是否存在price
dataList.forEach(v => {
    if (!newObject[v.price]) {
        newObject[v.price] = true
        newArray.push(v)
    } else {
        otherArray.push(v)
    }
});
// 合并数量的操作
otherArray.forEach(v => {
    newArray.forEach(k => {
        if (v.price === k.price) {
            k.amount += v.amount
        }
    });
});
// [{"id":5,"price":0.5,"amount":7},{"id":2,"price":1.5,"amount":9},{"id":3,"price":3.5,"amount":8},{"id":1,"price":5.5,"amount":5},{"id":7,"price":6.5,"amount":9}]
console.log(newArray)

这里面用到了JavaScript的数组对象排序和数组对象去重的知识,温故而知新,可以为师矣

如有错误,请多指教,谢谢!

原文地址:https://www.cnblogs.com/ykCoder/p/12553691.html