arr.reduce((參數一,參數二) ⇒ { }, 參數三)
const arr = [1,2,3,4,5,6,7,8]
arr.reduce((final, item) =>{
return final + item
},0)
// 36
將以下陣列取出重複值並相加
const data = [
{product_id: "-Lr8YllJkIewLhA7DCNU", title: "碗豆乳清蛋白粉", qty: 7, size: "草莓", price: "3000"},
{product_id: "-Lr8YllJkIewLhA7DCNU", title: "碗豆乳清蛋白粉", qty: 1, size: "草莓", price: "3000"},
{product_id: "-Lr8YllJkIewLhA7DCNU", title: "碗豆乳清蛋白粉", qty: 1, size: "巧克力", price: "3000"},
{product_id: "-LyWmWDrUg0qWmvJmHmJ", title: "皮革腰帶", qty: 1, size: "L", price: "1800"},
{product_id: "-LyWmWDrUg0qWmvJmHmJ", title: "皮革腰帶", qty: 1, size: "M", price: "1800"},
{product_id: "-LyWmWDrUg0qWmvJmHmJ", title: "皮革腰帶", qty: 1, size: "L", price: "1800"}
]
const data = [
{product_id: "-Lr8YllJkIewLhA7DCNU", title: "碗豆乳清蛋白粉", qty: 7, size: "草莓", price: "3000"},
{product_id: "-Lr8YllJkIewLhA7DCNU", title: "碗豆乳清蛋白粉", qty: 1, size: "草莓", price: "3000"},
{product_id: "-Lr8YllJkIewLhA7DCNU", title: "碗豆乳清蛋白粉", qty: 1, size: "巧克力", price: "3000"},
{product_id: "-LyWmWDrUg0qWmvJmHmJ", title: "皮革腰帶", qty: 1, size: "L", price: "1800"},
{product_id: "-LyWmWDrUg0qWmvJmHmJ", title: "皮革腰帶", qty: 1, size: "M", price: "1800"},
{product_id: "-LyWmWDrUg0qWmvJmHmJ", title: "皮革腰帶", qty: 1, size: "L", price: "1800"}
]
const filteredArr = data.reduce((final, current) => {
// 判斷數值(id, size)是否重複
const repeatItem = final.some(item => item.product_id === current.product_id && item.size === current.size)
console.log('final' ,final)
if(repeatItem){
// 重複時總數(qty)相加
// current為重複的值,forEach的item為不重複的值
// 再次判斷有重複的值才相加
final.forEach(item => { if(item.product_id === current.product_id && item.size === current.size) console.log('current',current),console.log('item',item)})
} else {
// 不重複時代表累加陣列(final)無該筆資料,做push
final.push(current)
}
return final
}, [])