【问题标题】:Javascript reducing to the sum of an array of arrays of integers [duplicate]Javascript减少为整数数组数组的总和[重复]
【发布时间】:2021-01-22 21:06:44
【问题描述】:

我有一个整数数组,看起来像这样[[5, 3], [2,1], [4, 3]],我期望的输出是[8, 3, 7],但我的reduce函数似乎缺少一些东西,因为我得到了一个@数组987654323@ 喜欢 [undefined, undefined, undefined],因为 n=3

如何获取数组中每个数组的总和并将其加载到数组中?

const reducer = (accumulator, currentValue) => accumulator + currentValue;

const dayArray = [[3,5],[4,6],[8,2]];

const twoWeekArray = dayArray.map((day, index) => {
  return day.reduce(reducer);
});

console.log(twoWeekArray);

【问题讨论】:

  • 你不会从地图的箭头函数返回
  • 编辑返回值

标签: javascript arrays


【解决方案1】:

你忘记返回了:

dayArray = [[3,5],[4,6],[8,2]];
twoWeekArray = dayArray.map((day, index) => {
    return day.reduce(function (a, b) {
        return a + b;
    });
});

【讨论】:

  • 顺便说一句,您还可以使用箭头功能。在这种情况下,您无需返回。
【解决方案2】:

给你...

const subject = [[5, 3], [2,1], [4, 3]]

const result = 
  subject.map((elem) => 
    elem.reduce((acum, current) =>
      acum = acum + current,
      0
    )
   )
   

console.log(result)

【讨论】:

  • 如果我们不知道每个数组中值的数量怎么办?
  • 我更改了它以适应您的新要求。
猜你喜欢
  • 1970-01-01
  • 2021-03-10
  • 2015-06-19
  • 2023-02-24
  • 2020-12-07
  • 2021-04-02
  • 2019-01-26
  • 1970-01-01
  • 2016-01-19
相关资源
最近更新 更多