13
头图

什么是reduce函数

  1. reduce 方法对数组中的每个元素按序执行一个提供的 reducer 函数
  2. 每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。

函数组成

reduce(callbackFn)
reduce(callbackFn, initialValue)

函数具体内容

  1. reduce 方法是一个迭代方法。
  2. 它按升序对数组中的所有元素运行一个“reducer”回调函数,并将它们累积到一个单一的值中。
  3. 每次调用时,callbackFn 的返回值都作为 accumulator 参数传递到下一次调用中。
  4. accumulator 的最终值(也就是在数组的最后一次迭代中从 callbackFn 返回的值)将作为 reduce() 的返回值。

函数示例

1.求和函数

const sum = (arr) => arr.reduce((acc, cur) => acc + cur, 0);
//累计值为acc
//当前值为cur
//初始值为initialValue 为0
let arr = [1, 2, 3, 4, 5];
console.log("参数为:", arr);
console.log("总和为:", sum(arr));

2.求积函数

const product = (arr) => arr.reduce((acc, curr) => acc * curr, 1);
let arr1 = [1, 2, 3, 4, 5];
console.log("参数为:", arr1);
console.log("乘积为:", product(arr1));

3.扁平化数组

const flatten = (arr) => arr.reduce((acc, curr) => acc.concat(curr), []);
let arr = [[1, 2], [3, 4], [5]];
console.log("参数为:", arr);
console.log("结果为:", flatten(arr));

4.计算平均值(类似求和)

const average = (arr) => arr.reduce((acc, curr) => acc + curr, 0) / arr.length;
let arr = [1, 2, 3, 4, 5];
console.log("参数为:", arr);
console.log("结果为:", average(arr));

5.最大值

const max = (arr) => arr.reduce((acc, curr) => Math.max(acc, curr), Number.NEGATIVE_INFINITY);
let arr = [1, 2, 3, 4, 5];
console.log("参数为:", arr);
console.log("结果为:", max(arr));

6.最小值

const min = (arr) => arr.reduce((acc, curr) => Math.min(acc, curr), Number.POSITIVE_INFINITY);
let arr = [1, 2, 3, 4, 5];
console.log("参数为:", arr);
console.log("结果为:", min(arr));

7.阶乘函数

const factorial = (n) => Array.from({ length: n }, (_, i) => i + 1).reduce((acc, curr) => acc * curr, 1);
//  Array.from({ length: n }, (_, i) => i + 1) 生成数组数据 [1,2,3,4,5]
console.log("参数为:", 5);
console.log("结果为:", factorial(5));

8.数组去重

const unique = (arr) => arr.reduce((acc, curr) => acc.includes(curr) ? acc : [...acc, curr], []);
let arr = [1, 2,3,4,2, 3, 4, 5];
console.log("参数为:", arr);
console.log("结果为:", unique(arr));

9.元素计数

const countOccurrences = (arr) => arr.reduce((acc, curr) => {
    acc[curr] = (acc[curr] || 0) + 1;
    return acc;
}, {});

let arr = [1, 2,3,4,2, 3, 4, 5];
console.log("参数为:", arr);
console.log("结果为:", countOccurrences(arr));

10.并集函数

const union = (...arrays) => arrays.reduce((acc, curr) => [...new Set([...acc, ...curr])], []);

let arr = [1, 2,3,4,2, 3, 4, 5];
let arr1 = [1, 2, 3, 4, 5];
console.log("参数为:", arr,arr1);
console.log("结果为:", union(arr,arr1));

11.交集函数

const intersection = (...arrays) => arrays.reduce((acc, curr) => acc.filter(value => curr.includes(value)));

let arr = [1, 2,3,4,2, 3, 4, 5];
let arr1 = [1, 2, 3, 4, 5];
console.log("参数为:", arr,arr1);
console.log("结果为:", intersection(arr,arr1));

12.差集函数

const difference = (arr1, arr2) => arr1.reduce((acc, curr) => arr2.includes(curr) ? acc : [...acc, curr], []);

let arr = [1, 2,3,4,2, 3, 4, 5,9];
let arr1 = [1, 2, 3, 4, 5,7,8];
console.log("参数为:", arr,arr1);
console.log("结果为:", difference(arr,arr1));

13.对称差集函数

const difference = (arr1, arr2) => arr1.reduce((acc, curr) => arr2.includes(curr) ? acc : [...acc, curr], []);
const symmetricDifference = (arr1, arr2) => [...difference(arr1, arr2), ...difference(arr2, arr1)];
let arr = [1, 2,3,4,2, 3, 4, 5,9];
let arr1 = [1, 2, 3, 4, 5,7,8];
console.log("参数为:", arr,arr1);
console.log("结果为:", symmetricDifference(arr,arr1));

14.切片函数

const chunk = (arr, size) => arr.reduce((acc, _, i) => i % size === 0 ? [...acc, arr.slice(i, i + size)] : acc, []);

let arr = [1, 2,3,4,2, 3, 4, 5,9];
console.log("参数为:", arr);
console.log("结果为:", chunk(arr,4));

15.分组函数

const groupBy = (arr, key) => arr.reduce((acc, obj) => {
    const groupKey = obj[key];
    acc[groupKey] = [...(acc[groupKey] || []), obj];
    return acc;
}, {});

let arr = [{ id: 1, name: '微芒不朽' }, { id: 2, name: '微芒' }, { id: 1, name: '微芒不朽' }];
console.log("参数为:", arr);
console.log("结果为:", groupBy(arr,"name"));

16.去除falsy值

// 16. 数组去除假值
const compact = (arr) => arr.reduce((acc, curr) => curr ? [...acc, curr] : acc, []);
let arr = [0, 1, false, 2, '', 3]
console.log("参数为:", arr);
console.log("结果为:", compact(arr,"name"));

17.去除空元素

const removeEmpty = (arr) => arr.reduce((acc, curr) => curr ? [...acc, curr] : acc, []);

let arr = [0, 1, null, 2,undefined, '', 3]
console.log("参数为:", arr);
console.log("结果为:", removeEmpty(arr,"name"));

18.去除指定元素

const removeItem = (arr, item) => arr.reduce((acc, curr) => curr === item ? acc : [...acc, curr], []);
let arr = [1, 2, 3, 4, 2, 5]
console.log("参数为:", arr);
console.log("结果为:", removeItem(arr,2));

19.元素映射

const mapArray = (arr, fn) => arr.reduce((acc, curr) => [...acc, fn(curr)], []);
let arr = [1, 2, 3, 4, 2, 5]
console.log("参数为:", arr,(x)=>x+2);
console.log("结果为:", mapArray(arr,(x)=>x+2));

19.元素过滤

const filterArray = (arr, fn) => arr.reduce((acc, curr) => fn(curr) ? [...acc, curr] : acc, []);
let arr = [1, 2, 3, 4, 2, 5]
console.log("参数为:", arr,(x) => x % 2 === 0);
console.log("结果为:", filterArray(arr,(x) => x % 2 === 0));

console.log样式函数【重写console.log】

function randomColor() {
  let r = Math.floor(Math.random()*256);
  let g = Math.floor(Math.random()*256);
  let b = Math.floor(Math.random()*256);
  //返回随机生成的颜色
  return "rgb("+r+","+g+","+b+")";
}
console.log = (function(oriLogFunc){
  return function(...data)
  {
    const icons = ["🌵", "🎍", "🐾", "🌀", "🐚", "🥝", "🥜", "🥕", "🥒", "🌽", "🍒", "🍅", "🍑", "🍋", "🍈", "🌶", "🌰", "🍠", "🍆", "🍄", "🍐", "🍌", "🍍", "🍇", "🍏", "🍓", "🍎", "🍊", "🐴", "🐗", "🦄", "🐑", "🐶", "🐔", "🐼", "🐒", "🌝", "💄", "💋", "👠", "👗", "👙", "🧣", "🍰", "🍭", "🍳", "🎄", "🎱", "⚽", "🏀", "🎵", "🚄", "⭕", "❌", "❓", "❗", "💯"]
    const icon = icons[Math.floor(Math.random() * icons.length)];
    const bgColor = randomColor()
    const color = randomColor()
    oriLogFunc.call(console,`%c ${icon} `, `border-radius:5px;padding:12px;border:1px solid #000;color: #43bb88;font-size: 16px;font-weight: bold;text-decoration: underline;`, ...data);
  }
})(console.log);

参考资料

  1. https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Refer...
  2. https://www.jianshu.com/p/a2f2a7eeb662

微芒不朽
1.2k 声望1.3k 粉丝