JavaScript reduce方法使用方法介绍

1. reduce方法的使用

Array.prototype.reduce(callBack(previousValue, currentValue, currentIndex), initialValue)

reduce是数组的一个高阶方法,用来实现对数组的累加计算

var arr = ['a', 'b', 'c'];
var str = arr.reduce(function (previousValue, currentValue, currentIndex) {
  return previousValue + currentValue;
  });
console.log(str); //abc
var str = arr.reduce(function (previousValue, currentValue, currentIndex) {
  return previousValue + currentValue;
}, 's');
console.log(str); //sabc

reduce的回调函数中一共有4个参数:

  • previous 表示计算的前一个值
  • currentValue 是正在被计算的值
  • currentIndex 是正在计算的索引
  • initialValue 设置累加的初始值

在数组遍历的时候,回调函数的返回值会累加给previousValue,一直到数组遍历完毕返回这个累加值。

在没有传递initialValue的情况下,首次累加的时候previousValue为数组的第1项,currentValue为数组的第2项,当传递了initialValue的时候previousValue初始值为initialValue,currentValue初始值为数组的第一项

2. reduce数组的使用场景

2.1 扁平化数组

使用reduce实现Array.prototype.flat的功能

const arr = [[1, 2, 3], [4, 5, 6, 7, 8], [9]];
const flat = arr.reduce((previousValue, currentValue) => {
   return previousValue.concat(currentValue);
});
console.log(flat); //[1, 2, 3, 4, 5, 6, 7, 8, 9]

2.2 数组去重

const arr = [1, 2, 5, 2, 5, 5];
const deduplication = arr.reduce((previousValue, currentValue) => {
  return previousValue.includes(currentValue) ? previousValue : previousValue.concat([currentValue]);
}, []);
console.log(deduplication);

2.3 计算数组最大/最小值

const arr = [2, 5, 1, 88, 12, -21, 33, 10, 75];
const maxVal = arr.reduce((previousValue, currentValue) => Math.max(previousValue, currentValue));
console.log(maxVal); //8

2.4 数组求和

const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((previousValue, currentValue) => previousValue + currentValue);
console.log(sum); //15

2.5 计算数组中元素的出现次数

const arr = ['a', 'c', 'b', 'a', 'c', 'e'];
const countedCharacter = arr.reduce((previousValue, currentValue) => {
if (currentValue in previousValue) {
  return { ...previousValue, [currentValue]: previousValue[currentValue] + 1 };
} else {
    return { ...previousValue, [currentValue]: 1 };
  };
}, {});
console.log(countedCharacter); //{a: 2, c: 2, b: 1, e: 1};

3. 操作对象

累加对象数组里面的值

const arr = [{ x: 1 }, { x: 2 }, { x: 3 }];
const sum = arr.reduce((previousValue, currentValue) =>
 previousValue + currentValue.x, 0);
console.log(sum); //6

4. 使用reduce代替.filter().map()

使用reduce可以同时完成过滤合映射,不需要遍历两次数组

const arr = [81, 92, 67, 100, 79];
const scoreArr = arr.filter(s => s > 80).map(val => ({ score: val }));
const scoreArr1 = arr.reduce((previousValue, currentValue) => {
  if (currentValue > 80) { return previousValue.concat([{ score: currentValue }]) } else {
    return previousValue;
  }
}, []);
console.log(scoreArr); //[{score: 81}, {score: 92}, {score: 100}]
console.log(scoreArr1); //[{score: 81}, {score: 92}, {score: 100}]

5. 按顺序执行promise

function p1(num) {
  return new Promise((rs, rj) => {
    setTimeout(() => {
      rs(num + 5);
    }, 100);
  });
 };
function p2(num) {
  return new Promise((rs, rj) => {
    setTimeout(() => {
      rs(num * 2);
    }, 300);
  });
 };
function p3(num) {
  return new Promise((rs, rj) => {
    rs(num - 3);
  })
 };
//链式调用
Promise.resolve(10)
  .then(p1)
  .then(p2)
  .then(p3)
  .then(res => console.log(res)) ;  //27
//使用reduce执行promise
var arr = [p1, p2, p3];
var lastPromise = arr.reduce((previousPromise, currentPromise) => previousPromise.then(currentPromise), Promise.resolve(10));
lastPromise.then(res => console.log(res)); //27

6. 使用compose函数组合实现管道

管道(Pipe)是指输入一个值,依次经过管道(有序的函数运算)后输出这个值,是函数编程的核心思想

function add10(num) {
  return num + 10;
};
function multipl2(num) {
  return num * 2;
};
function divide3(num) {
  return num / 3;
};
const compose = (fns) => (initialValue) => fns.reduce((previous, current) => current(previous), initialValue);
const calculate1 = compose([add10, divide3]);
const calculate2 = compose([divide3, add10, multipl2]);
console.log(calculate1(20)); //10
console.log(calculate2(9)); //26

原文地址:https://blog.csdn.net/qq_44621394/article/details/126852821