【问题标题】:Using reduce inside map在 map 中使用 reduce
【发布时间】:2022-01-08 02:29:44
【问题描述】:

每当我想在 map 函数中使用 reduce 时,我都会收到错误消息“reduce 不是函数”。

我有一个数组,我通过 2 个键进行映射。日期和金额。下面是包含对象的数组。

const dividendArrayFiltered = [
    {
        "date": "2021-11-09",
        "amount": 0.5
    },
    {
        "date": "2021-11-08",
        "amount": 0.5
    },
    {
        "date": "2021-11-08",
        "amount": 0.5
    },
    {
        "date": "2021-11-11",
        "amount": 1
    },
    {
        "date": "2021-11-11",
        "amount": 1
    }
]

在这张地图中,我想减少相同日期的值。

这是给出错误的代码。不太清楚为什么 reduce 功能不起作用。希望你能帮帮我。谢谢!

const summedDividend = dividendArrayFiltered.map(({ date, amount }) => {
    const grouped = date.reduce(
      (a, d, i) => a.set(d, (a.get(d) ?? 0) + amount[i]),
      new Map()
    );

    return {
      date: [...grouped.keys()],
      amount: [...grouped.values()],
    };
  });

【问题讨论】:

  • 你根本不想map,你只想直接reduce原始数组。
  • 你不能映射一个对象,你可以在 Object.entries 中转换它

标签: javascript reduce


【解决方案1】:

您自己的解决方案不起作用,因为在 map-function 内部,您只能访问当前项目,而不是数组,但 reduce-function 只能用于数组。

替代解决方案

您可以创建一个空数组,在其中仅推送原始数组中的这些项目,这些项目的日期与新数组中的项目之一不同。

  let uniqueArray = [] 

  // iterate through all array elements
  dividendArrayFiltered.forEach((item) => {
    // check if an element with the current item date exists in your new uniqueArray and which position index it has
    const itemPos = uniqueArray.findIndex(uniqueItem => uniqueItem.date == item.date)
    // if the index is negative, it's not included in the array, so you push your item to the new array
    if(itemPos < 0) {
      uniqueArray.push(item)
    }
    // if it's included, you take the old amount and add your new value
    else {
      uniqueArray[itemPos].amount = uniqueArray[itemPos].amount + item.amount;
    }
  });

  console.log(uniqueArray);

uniqueArray 中现在只有唯一的日期项。

【讨论】:

  • 感谢您帮助我,不胜感激!但是,这会删除重复项。我想合并副本。所以 "date": "2021-11-11" 的数量是 2 而不是 1。
  • 我没有看到你想总结金额,我已经编辑了我的答案,所以它现在应该可以按照你希望的方式工作了。
【解决方案2】:

你可以直接减少原始数组,也可以使用findIndex()

const dividendArrayFiltered = [
  { date: '2021-11-09', amount: 0.5 },
  { date: '2021-11-08', amount: 0.5 },
  { date: '2021-11-08', amount: 0.5 },
  { date: '2021-11-11', amount: 1 },
  { date: '2021-11-11', amount: 1 }
]

const grouped = dividendArrayFiltered.reduce((a, c) => {
  const dateIndex = a.findIndex(o => o.date === c.date)
  if (dateIndex !== -1) a[dateIndex].amount += c.amount
  else a.push({ date: c.date, amount: c.amount })

  return a
}, [])

console.log(grouped)
.as-console-wrapper { min-height: 100% }

【讨论】:

  • 真棒@aerial301,正是我需要的!
猜你喜欢
  • 1970-01-01
  • 2020-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-27
  • 2013-01-29
相关资源
最近更新 更多