简体   繁体   English

如何对 JavaScript 中具有相同值的数组求和?

[英]How to sum up array with same values in JavaScript?

This is my array which I'm pulling from Firebase with a listener.这是我的数组,我从 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"}]

I want this array to sum up all values on the same day, and return just one with the summed amount.我希望这个数组在同一天总结所有值,并只返回一个总和。 So I can use it for a chart in React Native with victory native.所以我可以将它用于 React Native 中带有胜利原生的图表。

This is my code, which is working fine, but I've been looking and looking all over the internet on how, to sum up, but no luck so far!这是我的代码,它运行良好,但我一直在互联网上寻找如何总结,但到目前为止还没有运气!

  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)
  })

Any help or advice will be much appreciated my friends!任何帮助或建议将不胜感激我的朋友!

Reduce array function can solve your problem.减少数组 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)
  1. Create a new object that can store key/value pairs where the key is the date.创建一个新的 object 可以存储键/值对,其中键是日期。
  2. Iterate over the objects adding the date as the key if it doesn't exist, and initialising it to an object with a date, and an amount set to zero.如果日期不存在,则迭代对象添加日期作为键,并将其初始化为 object,日期和数量设置为零。
  3. Add the current amount value to the amount store in the object for that date.将该日期的当前金额值添加到 object 中的金额存储中。
  4. Finally, after the loop is complete, use Object.values to get those objects into a new array.最后,循环完成后,使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM