如何在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中用它来制作一张带有胜利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)
})

任何帮助或建议都将不胜感激,我的朋友们!

Reduce数组函数可以解决您的问题。

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)
  1. 创建一个新对象,该对象可以存储键/值对,其中键是日期
  2. 在对象上迭代,如果不存在,则添加日期作为关键字,并将其初始化为具有日期和数量设置为零的对象
  3. 将当前金额值添加到对象中该日期的金额存储中
  4. 最后,循环完成后,使用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));

相关内容

  • 没有找到相关文章

最新更新