[英]How to sum up array with same values in JavaScript?
這是我的數組,我從 Firebase 和一個監聽器拉出來。
[{"Amount": "40", "Day": "08/31/2022"}, {"Amount": "300", "Day": "09/01/2022"}, {"Amount": "1715", "Day": "08/31/2022"}, {"Amount": "250", "Day": "08/31/2022"}, {"Amount": "100", "Day": "08/31/2022"}, {"Amount": "200", "Day": "08/31/2022"}]
我希望這個數組在同一天總結所有值,並只返回一個總和。 所以我可以將它用於 React Native 中帶有勝利原生的圖表。
這是我的代碼,它運行良好,但我一直在互聯網上尋找如何總結,但到目前為止還沒有運氣!
const q = query(collection(db, "users"), where("moneda", "==", "$"));
const unsubscribe = onSnapshot(q,(querySnapshot) => {
const dolarCurrency = [];
const months =[];
querySnapshot.forEach((doc) =>{
dolarCurrency.push(doc.data().cantidad);
months.push(doc.data().fecha)
})
const hash = months.map((Day) => ({ Day }));
const hashDolar = dolarCurrency.map(( Amount ) => ({ Amount }))
const output = hash.map(({Day},i) => ({Day, ...hashDolar[i]}));
console.log(output)
})
任何幫助或建議將不勝感激我的朋友!
減少數組 function 可以解決您的問題。
const output = [{"Amount": "40", "Day": "08/31/2022"}, {"Amount": "300", "Day": "09/01/2022"}, {"Amount": "1715", "Day": "08/31/2022"}, {"Amount": "250", "Day": "08/31/2022"}, {"Amount": "100", "Day": "08/31/2022"}, {"Amount": "200", "Day": "08/31/2022"}]
const sum = output.reduce((acc, cur)=> {
const found = acc.find(val => val.Day === cur.Day)
if(found){
found.Amount+=Number(cur.Amount)
}
else{
acc.push({...cur, Amount: Number(cur.Amount)})
}
return acc
}, [])
console.log(sum)
Object.values
將這些對象放入一個新數組中。 const arr = [{"Amount": "40", "Day": "08/31/2022"}, {"Amount": "300", "Day": "09/01/2022"}, {"Amount": "1715", "Day": "08/31/2022"}, {"Amount": "250", "Day": "08/31/2022"}, {"Amount": "100", "Day": "08/31/2022"}, {"Amount": "200", "Day": "08/31/2022"}]; const out = {}; for (const { Amount, Day } of arr) { out[Day]??= { Day, Amount: 0 }; const subtotal = out[Day].Amount + Number(Amount); out[Day] = {...out[Day], Amount: subtotal }; } console.log(Object.values(out));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.