【发布时间】:2021-08-19 05:38:42
【问题描述】:
我有数组
array = [
{ period: 1, currency: 1, cost: 100, count: 10 },
{ period: 1, currency: 2, cost: 200, count: 10 },
{ period: 2, currency: 1, cost: 300, count: 20 },
{ period: 3, currency: 3, cost: 400, count: 30 }
]
我需要你将 cost 与具有相同 period 和不同 currency 的情况相加,但不会将 count 相加,并且结果是两者之一,因为它们将相同的period。
例如:
period = 1, sum(cost) = 300 y count = 10
period = 2, sum(cost) = 300 y count = 20
period = 3, sum(cost) = 400 y count = 30
我该怎么做?谢谢
【问题讨论】:
-
到目前为止你尝试了什么?
-
您将需要根据您的要求迭代数组和组。您很可能想研究使用“array.reduce”。如果 2 个条目的期间和货币相同,预期的行为是什么?
-
@Nick 尝试分两部分做,一方面是同期成本的总和,另一方面是减少数组并获得每个时期的计数的函数。
-
@MateuszSiniarsk i是的,你必须使用reduce,同一时期和货币没有两个或更多条目。如何正确使用reduce来实现它?
标签: javascript arrays reactjs conditional-statements