最近看到一個比較有趣的問題,記錄一下自己的解決方法。
具體代碼如下:
/*
* 合並相同價格(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的數組對象排序和數組對象去重的知識,溫故而知新,可以為師矣
。
如有錯誤,請多指教,謝謝!