无法理解这个特定的 Array reduce 方法

Trouble understanding this particular Array reduce method

我需要详细解释我在对象数组上使用的 Array reduce 方法。 Array reduce 方法根据比赛日值将给定数组转换为对象数组。因此它过滤数组并将具有相同比赛日值的对象存储在嵌套对象数组中。我知道减速器通常只在这种情况下做什么,我遗漏了一些东西。谁可以给我解释一下这个?任何帮助将不胜感激。

const data = [
{ id: 301998, season: 2020-2021, utcDate: "2020-09-12T16:45:00Z", status: "FINISHED", matchday: 1 },
{ id: 301999, season: 2020-2021, utcDate: "2020-09-12T18:00:00Z", status: "FINISHED", matchday: 1 },
{ id: 302000, season: 2020-2021, utcDate: "2020-09-12T19:00:00Z", status: "FINISHED", matchday: 1 },


{ id: 302006, season: 2020-2021, utcDate: "2020-09-18T18:00:00Z", status: "FINISHED", matchday: 2 },
{ id: 302007, season: 2020-2021, utcDate: "2020-09-19T14:30:00Z", status: "FINISHED", matchday: 2 },
{ id: 302008, season: 2020-2021, utcDate: "2020-09-19T16:45:00Z", status: "FINISHED", matchday: 2 }
]

let res = Object.values(
data.reduce((acc, m) => {

    acc[ m.matchday ] = acc[ m.matchday ] || [];
    acc[ m.matchday ].push(m);

    return acc;
   }, {})
);
console.log(res) // =>  [ [{…}, {…}, {…}], [{…}, {…}, {…}] ]

Object.values

Object.values() 方法 returns 给定对象自身的可枚举 属性 值的数组,与 for...in 循环提供的顺序相同。 (唯一的区别是 for...in 循环也枚举原型链中的属性。)

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.values(object1));
// expected output: Array ["somestring", 42, false]

归约函数

reduce() 方法对数组的每个元素执行(您提供的)reducer 函数,从而产生单个输出值。

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

reducer 函数有四个参数:

reducer 函数有四个参数:

  1. 累加器
  2. 当前值
  3. 当前指数
  4. 源数组

在你的问题中,

data 数组缩减为以下结构的对象 -

obj = {
      1: [{ id: 301998, season: 2020-2021, utcDate: "2020-09-12T16:45:00Z", status: "FINISHED", matchday: 1 }, ...],
      2: [{ id: 23412, season: 2020-2021, utcDate: "2020-09-12T16:45:00Z", status: "FINISHED", matchday: 2 }, ...]
}

现在,Object.values 上面的对象只是 returns 上面对象的 (obj) 值的返回数组。

The returned array would be of length = 'no of unique match days present in data array'

输出-

[
   [{ id: 301998, season: 2020-2021, utcDate: "2020-09-12T16:45:00Z", status: "FINISHED", matchday: 1 }, ...],
   [{ id: 23412, season: 2020-2021, utcDate: "2020-09-12T16:45:00Z", status: "FINISHED", matchday: 2 }, ...]
]