有人可以用最简单的术语向我解释 reduce 方法到底是如何工作的吗?

Can someone explain to me in the simplest of terms how the reduce method works exactly?

提问人:ofg 提问时间:10/18/2023 更新时间:10/18/2023 访问量:70

问:

我正在做一个来自 Odin Project 的练习,我需要使用 array.reduce 方法在对象数组(由不同年龄的人组成)中找到最年长的人。我通过查找解决方案尝试编码来让它工作。我花了几天时间试图弄清楚reduce方法如何像在这种情况下一样工作,但我不明白。

从我收集到的信息来看,一个函数通常传递给reduce方法,其中包含两个参数,这些参数始终表示1)数组的累积值和2)正在迭代的当前元素。但是在我下面发布的代码中,参数似乎以某种方式工作,它们用于比较数组中的不同对象。

我的问题是:参数“oldest”清楚地表示数组中最年长的人。那是一个人一个元素。当该参数应该表示数组的累积值,从而将多个元素加在一起时,这是如何工作的?

我没有得到什么?

  const findTheOldest = function(array) { 
// Use reduce method to reduce the array by comparing current age with previous age
  return array.reduce((oldest, currentPerson) => {
    // oldestAge gets the age of the oldest person's year of death and birth
    const oldestAge = getAge(oldest.yearOfBirth, oldest.yearOfDeath);

    // currentAge gets the age of the current person's year of death and birth
    const currentAge = getAge(currentPerson.yearOfBirth, currentPerson.yearOfDeath);

    // return name if current age is older than the oldest age, else return current oldest age
    return oldestAge < currentAge ? currentPerson : oldest;
  });

};

const getAge = function(birth, death) {
 if (!death) {
death = new Date().getFullYear(); // return current year using Date()
}
return death - birth; // else just return age using death minus birth

console.log(findTheOldest(people).name); // Ray
JavaScript 数组 方法

评论

0赞 Elvis Adomnica 10/18/2023
查看 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/...
3赞 jarmod 10/18/2023
累加器参数不必是任何内容的累加。它可以是你想要的任何东西。值、最高值、最低值、对象(如 )或任何在特定用例中有意义的值的总和。{red:2, blue:3, white:0}
0赞 ofg 10/18/2023
Jarmod - 啊哈,这让我更接近理解为什么代码会起作用。那么,我的问题是,所讨论的代码的哪一部分究竟决定了累加器参数的用途?
1赞 jarmod 10/18/2023
reducer 函数被多次调用(数组中每人一次)。它将存储在(累加器)中的人的年龄与存储在中的人的年龄进行比较,并返回年龄较大的人。然后,该老人是下一次调用 reducer 函数的累加器值,数组中的下一个人将传递给该函数。在任何给定时间,累加器都表示迄今为止找到的最年长的人(并且未定义第一次调用 reduce 函数),因为您没有发送初始值来减少。oldestcurrentPerson
1赞 jarmod 10/18/2023
对前面注释的更正 - 初始累加器值是数组中的第一个人称(它不是未定义的),并且 reduce 称为 N-1 次。在此处观看所有示例,尤其是最低/最高工资示例。

答:

1赞 Quentin 10/18/2023 #1

第一个值是从上一次迭代返回的值。

当您用作累加器时,您返回的值是累积值,并且通常会给它一个名称来表明这一点。reduce

例如:

[1,2,3].reduce( 
    (accumulator, current) =>  accumulator + current,
    0
);

对于问题中的代码,返回的值是前一个值和当前值的较早值,因此使用不同的名称。

1赞 jarmod 10/18/2023 #2

累加器参数不必是任何内容的累加。它可以是你想要的任何东西。值、最高值、最低值、频率计数对象(如 )或在特定用例中有意义的任何值的总和。{red:2, blue:3, white:0}

reduce函数的工作原理如下:

Reduce在数组的每个元素上执行用户提供的“Reducer”回调函数,按顺序传入前一个元素的计算的返回值。在数组的所有元素上运行 reducer 的最终结果是一个值。

请注意,如果您不提供初始累加器值,则 JavaScript 只需使用索引 0 处的数组元素作为初始累加器值,数组迭代从数组中的第 2 个元素开始。

以下是如何使用 reduce 解决各种问题的一些示例。第一种是典型的、经典的减少方案,用于对财产(工资)进行求和。第 2 个和第 3 个是常见的最小值/最大值示例。最后一个更复杂一些,它按某些属性(员工的团队)对值进行分组。

const employees = [
  { name: "joe", age: 23, salary: 12000, team: "sales" },
  { name: "mary", age: 41, salary: 15000, team: "hr" },
  { name: "bob", age: 37, salary: 13000, team: "eng" },
  { name: "alice", age: 21, salary: 11000, team: "eng" },
];

// What is the total payroll (initial accumulated value 0)?
const payroll = employees.reduce((total, current) => {
  return total + current.salary;
}, 0);

// Which is the youngest employee (no initial value)?
const youngest_employee = employees.reduce((youngest, current) => {
  return youngest.age < current.age ? youngest : current;
});

// Which is the highest paid employee (no initial value)?
const highest_paid_employee = employees.reduce((highest, current) => {
  return highest.salary > current.salary ? highest : current;
});

// Which employees work for each team (initial value is object with
// key/value pairs of team names to empty array of employee names)?
const team_employee_names = employees.reduce(
  (accumulator, current) => {
    accumulator[current.team].push(current.name);
    return accumulator;
  },
  { sales: [], hr: [], eng: [] }
);

console.log("Payroll:", payroll);
console.log("Youngest:", youngest_employee.name);
console.log("Highest paid:", highest_paid_employee.name);
console.log("Employee names by team:", team_employee_names);