Skip to content

Array.prototype.reduce #16

Open
Open

Description

@aicekiller

对数组中每个元素执行一次传入的函数。

arr.reduce((acc,cur,index,array)=>{}, initialValue)
// acc  函数执行的返回值或者initialValue
// cur  当前正在处理的值
// index arr的索引(可选)
// array === arr(可选)

reduce()回调函数第一次执行时,如果没有传initialValue,那么acc为array[0],cur为array[1],index索引为1;
如果传了initialValue,那么acc为initialValue,cur为array[0],index索引为0。

const arr = [1,2,3]
arr.reduce((acc, cur) => {
    console.log(acc)
    console.log(cur)
});
// 函数执行两次
// 第一次
// 1  没有传initialValue,acc为数组的第一个元素1
// 2  没有传initialValue,cur为数组中第二个元素2

// 第二次
// undefined 没有显式的返回值
// 3

空数组且没有传initialValue,会报错。
image
如果数组仅有一个元素且没有传initialValue,或者空数组有initialValue,直接返回数组中的元素或initialValue,回调函数不会被执行。

use

// 取对象数组中最大值
const arr = [
    { name: "lxcan", age: 20 },
    { name: "ican", age: 25 },
    { name: "ican", age: 25 },
    { name: "splendid", age: 18 },
]

arr.reduce((acc, cur) => (acc.age > cur.age ? acc : cur))

// 去重
const obj = {}
arr.reduce((acc, cur) => {
    obj[cur.name] ? "" : obj[cur.name] = true && acc.push(cur);
    return acc;
}, [])

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions