javaScript

20个reduce高级用法

# 1. reduce()

reduce 作为 ES5 新增的常规数组方法之一,对比 forEach 、filter 和 map,在实际使用上好像有些被忽略,发现身边的人极少用它,导致这个如此强大的方法被逐渐埋没。 定义:对数组中的每个元素执行一个自定义的累计器,将其结果汇总为单个返回值

形式:array.reduce((t, v, i, a) => {}, initValue)

回调函数的参数 total(t):累计器完成计算的返回值(必选) value(v):当前元素(必选) index(i):当前元素的索引(可选) array(a):当前元素所属的数组对象(可选)

过程 以 t 作为累计结果的初始值,不设置 t 则以数组第一个元素为初始值 开始遍历,使用累计器处理 v,将 v 的映射结果累计到 t 上,结束此次循环,返回 t 进入下一次循环,重复上述操作,直至数组最后一个元素 结束遍历,返回最终的 t

reduce 的精华所在是将累计器逐个作用于数组成员上,把上一次输出的值作为下一次输入的值。下面举个简单的栗子,看看 reduce 的计算结果。

const arr = [3, 5, 1, 4, 2]; const a = arr.reduce((t, v) => t + v); // 等同于 const b = arr.reduce((t, v) => t + v, 0);

reduce 实质上是一个累计器函数,通过用户自定义的累计器对数组的元素进行自定义累计,得出一个由累计器生成的值。另外 reduce 还有一个胞弟 reduceRight,两个方法的功能其实是一样的,只不过 reduce 是升序执行,reduceRight 是降序执行。

# 2. 代替 map 和 filter

const arr = [0, 1, 2, 3];

// 代替 map:[0, 2, 4, 6]
const a = arr.map(v => v _ 2);
const b = arr.reduce((t, v) => [...t, v _ 2], []);

// 代替 filter:[2, 3]
const c = arr.filter(v => v > 1);
const d = arr.reduce((t, v) => v > 1 ? [...t, v] : t, []);

// 代替 map 和 filter:[4, 6]
const e = arr.map(v => v _ 2).filter(v => v > 2);
const f = arr.reduce((t, v) => v _ 2 > 2 ? [...t, v * 2] : t, []);

# 3. 数组分割

function Chunk(arr = [], size = 1) {
return arr.length ? arr.reduce((t, v) => (t[t.length - 1].length === size ? t.push([v]) : t[t.length - 1].push(v), t), [[]]) : [];
}

const arr = [1, 2, 3, 4, 5];
Chunk(arr, 2); // [[1, 2], [3, 4], [5]]

# 4. 数组过滤

function Difference(arr = [], oarr = []) {
  return arr.reduce((t, v) => (!oarr.includes(v) && t.push(v), t), []);
}

const arr1 = [1, 2, 3, 4, 5];
const arr2 = [2, 3, 6];
Difference(arr1, arr2); // [1, 4, 5]

# 5. 数组填充

function Fill(arr = [], val = '', start = 0, end = arr.length) {
  if (start < 0 || start >= end || end > arr.length) return arr;
  return [
    ...arr.slice(0, start),
    ...arr.slice(start, end).reduce((t, v) => (t.push(val || v), t), []),
    ...arr.slice(end, arr.length)
  ];
}

const arr = [0, 1, 2, 3, 4, 5, 6];
Fill(arr, 'aaa', 2, 5); // [0, 1, "aaa", "aaa", "aaa", 5, 6]

# 6. 数组扁平

function Flat(arr = []) {
  return arr.reduce((t, v) => t.concat(Array.isArray(v) ? Flat(v) : v), []);
}

const arr = [0, 1, [2, 3], [4, 5, [6, 7]], [8, [9, 10, [11, 12]]]];
Flat(arr); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

# 7. 数组去重

function Uniq(arr = []) {
  return arr.reduce((t, v) => (t.includes(v) ? t : [...t, v]), []);
}

const arr = [2, 1, 0, 3, 2, 1, 2];
Uniq(arr); // [2, 1, 0, 3]

# 8. 利用 filter 去重

const arr = [4,5,3,4,6,5,8,6];
const b = arr.filter((item, index, arr) => arr.indexOf(item, 0) === index;) // [4, 5, 3, 6, 8]
利用 hasOwnProperty 去重

const arr = [4,5,3,4,6,5,8,6];
function duplicate (arr) {
var obj = {};
return arr.filter(function(item, index, arr){
return obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true)
})
}
console.log(duplicate(arr)) // 4, 5, 3, 6, 8]
最便捷的方法: [...new Set(arr)]

const arr = [4,5,3,4,6,5,8,6];
console.log(Array.from(new Set(arr))) // [4, 5, 3, 6, 8]
console.log([...new Set(arr)]) // [4, 5, 3, 6, 8]

# 9. 数组最、最小值

function Max(arr = []) {
  return arr.reduce((t, v) => (t > v ? t : v));
}

function Min(arr = []) {
  return arr.reduce((t, v) => (t < v ? t : v));
}

const arr = [12, 45, 21, 65, 38, 76, 108, 43];
Max(arr); // 108
Min(arr); // 12

# 10. 数组成员独立拆解

function Unzip(arr = []) {
  return arr.reduce(
    (t, v) => (v.forEach((w, i) => t[i].push(w)), t),
    Array.from({ length: Math.max(...arr.map(v => v.length)) }).map(v => [])
  );
}

const arr = [
  ['a', 1, true],
  ['b', 2, false]
];
Unzip(arr); // [["a", "b"], [1, 2], [true, false]]

// 对数组成员个数进行统计
function Count(arr = []) {
  return arr.reduce((t, v) => ((t[v] = (t[v] || 0) + 1), t), {});
}

const arr = [0, 1, 1, 2, 2, 2];
Count(arr); // { 0: 1, 1: 2, 2: 3 }

// 对数组成员位置进行记录
function Position(arr = [], val) {
  return arr.reduce((t, v, i) => (v === val && t.push(i), t), []);
}

const arr = [2, 1, 5, 4, 2, 1, 6, 6, 7];
Position(arr, 2); // [0, 4]

// 对数组成员特性进行分组
function Group(arr = [], key) {
  return key
    ? arr.reduce(
        (t, v) => (!t[v[key]] && (t[v[key]] = []), t[v[key]].push(v), t),
        {}
      )
    : {};
}
const arr = [
  { area: 'GZ', name: 'YZW', age: 27 },
  { area: 'GZ', name: 'TYJ', age: 25 },
  { area: 'SZ', name: 'AAA', age: 23 },
  { area: 'FS', name: 'BBB', age: 21 },
  { area: 'SZ', name: 'CCC', age: 19 }
]; // 以地区 area 作为分组依据
Group(arr, 'area'); // { GZ: Array(2), SZ: Array(2), FS: Array(1) }

# 11.对数组成员包含的关键字进行统计

function Keyword(arr = [], keys = []) {
  return keys.reduce(
    (t, v) => (arr.some(w => w.includes(v)) && t.push(v), t),
    []
  );
}

const text = [
  '今天天气真好,我想出去钓鱼',
  '我一边看电视,一边写作业',
  '小明喜欢同桌的小红,又喜欢后桌的小君,真 TM 花心',
  '最近上班喜欢摸鱼的人实在太多了,代码不好好写,在想入非非'
];
const keyword = ['偷懒', '喜欢', '睡觉', '摸鱼', '真好', '一边', '明天'];
Keyword(text, keyword); // ["喜欢", "摸鱼", "真好", "一边"]

# 12.字符串翻转

function ReverseStr(str = '') {
  return str.split('').reduceRight((t, v) => t + v);
}

const str = 'reduce 最牛逼';
ReverseStr(str); // "逼牛最 ecuder"

# 13.累加累乘

function Accumulation(...vals) {
return vals.reduce((t, v) => t + v, 0);
}

function Multiplication(...vals) {
return vals.reduce((t, v) => t \* v, 1);
}

Accumulation(1, 2, 3, 4, 5); // 15
Multiplication(1, 2, 3, 4, 5); // 120

// 异步累计
async function AsyncTotal(arr = []) {
return arr.reduce(async(t, v) => {
const at = await t;
const todo = await Todo(v);
at[v] = todo;
return at;
}, Promise.resolve({}));
}

const result = await AsyncTotal(); // 需在 async 包围下使用

# 14. 斐波那契数列

function Fibonacci(len = 2) {
  const arr = [...new Array(len).keys()];
  return arr.reduce(
    (t, v, i) => (i > 1 && t.push(t[i - 1] + t[i - 2]), t),
    [0, 1]
  );
}

Fibonacci(10); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

# 15. 返回对象指定的键值

function GetKeys(obj = {}, keys = []) {
  return Object.keys(obj).reduce(
    (t, v) => (keys.includes(v) && (t[v] = obj[v]), t),
    {}
  );
}

const target = { a: 1, b: 2, c: 3, d: 4 };
const keyword = ['a', 'd'];
GetKeys(target, keyword); // { a: 1, d: 4 }

# 16 权重求和

const score = [
{ score: 90, subject: "chinese", weight: 0.5 },
{ score: 95, subject: "math", weight: 0.3 },
{ score: 85, subject: "english", weight: 0.2 }
];
const result = score.reduce((t, v) => t + v.score \* v.weight, 0); // 90.5

# 17. 数组转对象

const people = [
  { area: 'GZ', name: 'YZW', age: 27 },
  { area: 'SZ', name: 'TYJ', age: 25 }
];
const map = people.reduce((t, v) => {
  const { name, ...rest } = v;
  t[name] = rest;
  return t;
}, {}); // { YZW: {…}, TYJ: {…} }

// Redux Compose 函数原理
function Compose(...funs) {
  if (funs.length === 0) {
    return arg => arg;
  }
  if (funs.length === 1) {
    return funs[0];
  }
  return funs.reduce(
    (t, v) =>
      (...arg) =>
        t(v(...arg))
  );
}

# 18. for-in、forEach、map 和 reduce 性能

有些同学可能会问,reduce 的性能又如何呢?下面我们通过对 for-in、forEach、map 和 reduce 四个方法同时做 1~100000 的累加操作,看看四个方法各自的执行时间。

// 创建一个长度为 100000 的数组
const list = [...new Array(100000).keys()];

// for-in
console.time('for-in');
let result1 = 0;
for (let i = 0; i < list.length; i++) {
  result1 += i + 1;
}
console.log(result1);
console.timeEnd('for-in');

// forEach
console.time('forEach');
let result2 = 0;
list.forEach(v => (result2 += v + 1));
console.log(result2);
console.timeEnd('forEach');

// map
console.time('map');
let result3 = 0;
list.map(v => ((result3 += v + 1), v));
console.log(result3);
console.timeEnd('map');

// reduce
console.time('reduce');
const result4 = list.reduce((t, v) => t + v + 1, 0);
console.log(result4);
console.timeEnd('reduce');

// 累加操作
// 执行时间
// for-in 6.719970703125ms
// forEach 3.696044921875ms
// map 3.554931640625ms
// reduce 2.806884765625ms
上次更新: