Usage scenarios of reduce in js:

reduce is mainly used to combine multiple values ​​in an array or object into one value, and can perform specified operations on each element. Common usage scenarios include:

  1. Array summation, average value, maximum value, minimum value and other operations.

  2. Flattens a multidimensional array.

  3. Perform operations such as deduplication and sorting on the array.

  4. Group the elements of an array by an attribute.

  5. Combine and calculate the attribute values ​​of objects.

  6. Implement currying of functions.

  7. Implement chain calls.

"1" Array summation, average value, maximum value, minimum value and other operations;

// 求和
const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((prev, cur) => prev + cur, 0);
console.log(sum); // 15

// 求平均值
const arr = [1, 2, 3, 4, 5];
const avg = arr.reduce((prev, cur, index, arr) => {
  prev += cur;
  if (index === arr.length - 1) {
    return prev / arr.length;
  } else {
    return prev;
  }
}, 0);
console.log(avg); // 3

// 求最大值
const arr = [1, 2, 3, 4, 5];
const max = arr.reduce((prev, cur) => prev > cur ? prev : cur, arr[0]);
console.log(max); // 5

// 求最小值
const arr = [1, 2, 3, 4, 5];
const min = arr.reduce((prev, cur) => prev < cur ? prev : cur, arr[0]);
console.log(min); // 1


"2" Flattens multidimensional arrays.

In the callback function of the reduce method, it is judged whether the current element is an array, and if so, the flatten function is called recursively to perform the flattening operation; otherwise, the current element is added to the result array. Finally return the result array

const arr = [1, [2, [3, 4], 5], 6];

function flatten(arr) {
  return arr.reduce((prev, cur) => {
    if (Array.isArray(cur)) {
      return prev.concat(flatten(cur));
    } else {
      return prev.concat(cur);
    }
  }, []);
}

const flatArr = flatten(arr);
console.log(flatArr); // [1, 2, 3, 4, 5, 6]

 "3" Perform operations such as deduplication and sorting on the array

// 排序
const arr = [3, 1, 4, 2, 5];

const sortedArr = arr.reduce((prev, cur) => {
  const index = prev.findIndex(item => item > cur);
  if (index === -1) {
    prev.push(cur);
  } else {
    prev.splice(index, 0, cur);
  }
  return prev;
}, []);

console.log(sortedArr); // [1, 2, 3, 4, 5]

// 去重
const arr = [1, 2, 3, 2, 4, 1, 5];

const uniqueArr = arr.reduce((prev, cur) => {
  if (prev.indexOf(cur) === -1) {
    prev.push(cur);
  }
  return prev;
}, []);

console.log(uniqueArr); // [1, 2, 3, 4, 5]

"4" Group the elements in the array according to a certain attribute

// 将数组中的元素按照某个属性进行分组
const arr = [
  {id: 1, name: 'Alice'},
  {id: 2, name: 'Bob'},
  {id: 3, name: 'Charlie'},
  {id: 4, name: 'David'},
  {id: 5, name: 'Alice'}
];

const groupObj = arr.reduce((prev, cur) => {
  if (!prev[cur.name]) {
    prev[cur.name] = [];
  }
  prev[cur.name].push(cur);
  return prev;
}, {});

console.log(groupObj);
/*
{
  Alice: [
    {id: 1, name: 'Alice'},
    {id: 5, name: 'Alice'}
  ],
  Bob: [
    {id: 2, name: 'Bob'}
  ],
  Charlie: [
    {id: 3, name: 'Charlie'}
  ],
  David: [
    {id: 4, name: 'David'}
  ]
}

在reduce方法的回调函数中,使用一个空对象作为初始值,遍历数组中的每个元素,如果当前元素的name属性不存在于结果对象中,则在结果对象中新增一个空数组;然后将当前元素加入到对应的数组中。最终返回结果对象,其中的属性名就是按照name属性分组的标准。
*/

"5" Merge and calculate the attribute values ​​of objects

// 对象属性值合并
const objArr = [
  {name: 'Alice', age: 20},
  {name: 'Bob', age: 22},
  {name: 'Charlie', age: 25},
  {name: 'David', age: 21},
  {name: 'Alice', age: 23}
];

const groupObj = objArr.reduce((prev, cur) => {
  if (!prev[cur.name]) {
    prev[cur.name] = {name: cur.name, age: 0};
  }
  prev[cur.name].age += cur.age;
  return prev;
}, {});

console.log(groupObj);
/*
{
  Alice: {name: 'Alice', age: 43},
  Bob: {name: 'Bob', age: 22},
  Charlie: {name: 'Charlie', age: 25},
  David: {name: 'David', age: 21}
}
*/

// 对象属性值计算
const objArr = [
  {name: 'Alice', score: 80},
  {name: 'Bob', score: 90},
  {name: 'Charlie', score: 70},
  {name: 'David', score: 85},
  {name: 'Alice', score: 95}
];

const sum = objArr.reduce((prev, cur) => prev + cur.score, 0);

console.log(sum); // 420

"6" realizes currying of functions.

function curry(fn) {
  return function curried(...args) {
    if (args.length >= fn.length) {
      return fn.apply(this, args);
    } else {
      return function(...args2) {
        return curried.apply(this, args.concat(args2));
      }
    }
  }
}

function add(a, b, c) {
  return a + b + c;
}

const curriedAdd = curry(add);

console.log(curriedAdd(1)(2)(3)); // 6
console.log(curriedAdd(1, 2)(3)); // 6
console.log(curriedAdd(1)(2, 3)); // 6
console.log(curriedAdd(1, 2, 3)); // 6

在curry函数中,使用reduce方法对参数列表进行累加,如果参数列表长度大于等于函数的形参个数,则直接调用原函数;
否则返回一个新的包装函数,将新的参数列表和原有的参数列表合并后再次调用curried函数。最终返回原函数的计算结果。
通过这种方式,就可以实现函数的柯里化

「7」 Realize chain tuning

class Calc {
  constructor(initValue = 0) {
    this.value = initValue;
  }
  add(num) {
    this.value += num;
    return this;
  }
  sub(num) {
    this.value -= num;
    return this;
  }
  mul(num) {
    this.value *= num;
    return this;
  }
  div(num) {
    this.value /= num;
    return this;
  }
}

const calc = new Calc(10);

const result = calc.add(5).sub(3).mul(2).div(4).value;

console.log(result); // 3

在Calc类中,每个方法都返回this对象,这样就可以实现链式调用。
在链式调用的最后,通过访问value属性获取最终的计算结果。
在这个过程中,可以使用reduce方法对方法列表进行累加,从而实现链式调用

Guess you like

Origin blog.csdn.net/congxue666/article/details/130562099