TS 之 reduce

一.函数介绍

  • Array.reduce()方法是对数组进行遍历,返回一个计算后的值

  • 使用方法:

Array.reduce((acc, cur, idx, src) => { }, initialValue)

  • callback回调函数接收4个参数:
    Accumulator (acc) (累计器) 如果传入了initialValue,Accumulator的初始值就是initialValue,没传入就是数组的第一个值
    Current Value (cur) (当前值)
    Current Index (idx) (当前索引)如果传入了initialValue,索引从0开始,没传入从1开始
    Source Array (src) (源数组)

initialValue 指定的初始值,初始值可以是数字,数组,对象

二.例子

2.1.数组求和

const arr = [1, 2, 3, 4, 5, 6];
let c = arr.reduce((a, b) => {
    console.log(a, b);
    return a + b;
});
console.log(c);

2.2.对象数组求和

const arr = [
    {
        name: '张三',
        count: 1
    },
    {
        name: '李四',
        count: 2
    },
    {
        name: '王五',
        count: 3
    },
    {
        name: '赵六',
        count: 4
    }
];
/**
 * 对象数组求和
 * pre:number
 * cur:当前对象
 * 最后的0:初始值
 */
 const sum = arr.reduce((pre, cur) => {
    console.log(pre, cur);
    return pre + cur.count;
}, 0);
console.log(sum);

2.3.统计次数

/**
 * 统计字母出现的个数
 */
let str = 'HelloWorld';
let arrStr = str.split('');
type TNumb = {
    name: string;
    count: number;
};
let arrFinal = arrStr.reduce((acc: TNumb[], cur: string): TNumb[] => {
    let existItem = acc.find(it => it.name === cur);
    if (!existItem) {
        acc.push({ name: cur, count: 1 });
    } else {
        existItem.count++;
    }
    return acc;
}, []);
console.log(arrFinal);

2.4.求字符串数组中哪个出现的次数最多

let arr1 = ['李明', '韩梅梅', '张三', '李明', '李明', '张三', '韩梅梅', '李明', 'Jack', '韩梅梅'];
type TNumb = {
    name: string;
    count: number;
};
let arrFinal = arr1.reduce((acc: TNumb[], cur: string): TNumb[] => {
    let existItem = acc.find(it => it.name === cur);
    if (!existItem) {
        acc.push({ name: cur, count: 1 });
    } else {
        existItem.count++;
    }
    return acc;
}, []);
console.log(arrFinal);

let a = arrFinal.reduce((acc: TNumb, cur: TNumb) => {
    return acc.count > cur.count ? acc : cur;
});
console.log(a);

// 去重
let b = arrFinal.reduce((acc: string[], cur: TNumb) => {
    if (!acc.includes(cur.name)) {
        acc.push(cur.name);
    }
    return acc;
}, []);
console.log(b);

2.5.二维数组转一维数组

// 二维数组转一维数组
let numArr: number[][] = [];
numArr[0] = [1, 2, 3, 4];
numArr[1] = [5, 6, 7];
numArr[2] = [9, 10, 11];
let numArrNew = numArr.reduce((acc, cur) => {
    return acc.concat(cur);
}, []);
console.log(numArrNew);
posted @ 2022-12-16 07:54  his365  阅读(3089)  评论(0编辑  收藏  举报