【问题标题】:Get value of an array given a certain condition in reactjs在reactjs中给定特定条件获取数组的值
【发布时间】: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


【解决方案1】:

这是一种无需在其他循环中使用循环即可完成任务的方法。 result 最终成为一个对象,每个周期都有一个键。

const 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: 330 }
];

const result = array.reduce((all, el) => {
  if (all[el.period]) {
    all[el.period].cost += el.cost;
  } else {
    all[el.period] = { ...el };
  }
  return all;
}, {});

console.log(result[1]);
console.log(result[2]);
console.log(result[3]);

【讨论】:

    【解决方案2】:

    您可以使用给定的函数式数组方法解决此解决方案。

    let 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: 330 },
    ];
    
    const newArray = array.reduce((acc, elem) => {
      if (acc.some((accElem) => accElem.period === elem.period)) {
        return acc;
      }
      elem.sumCost = array
        .filter((e) => e.period === elem.period)
        .reduce((acc, e) => acc + e.cost, 0);
      return acc.concat(elem);
    }, []);
    
    console.log(newArray);

    计数、货币和成本变量等于匹配变量中第一个元素的字段。

    【讨论】:

    • 我可能建议不要将 cost 键留在最终数组中,因为它在聚合中没有真正的意义。此外,这似乎在规模上可能相当低效(循环内的循环)。我怀疑这个问题的规模是否重要,但如果可能的话,尽量避免是合理的。
    猜你喜欢
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    相关资源
    最近更新 更多