JS中reduce()的多种用法

414 阅读1分钟

reduce()方法将数组中的所有元素还原成一个单一的输出值, 输出值可以是数字,对象或者字符串.

reduce()方法有两个参数, 第一个是回调函数, 第二个是初始值.

eg1:

const numArr = [1, 2, 3, 4];

const total = numArr.reduce((initValue, currentValue) => {
    console.log(`initValue: ${initValue}; currentValue: ${currentValue}`);
    return initValue + currentValue;
}, 0);

console.log(`total: ${total}`);

// initValue: 0; currentValue: 1
// initValue: 1; currentValue: 2
// initValue: 3; currentValue: 3
// initValue: 6; currentValue: 4
// total: 10

eg2: 对数组的所有值求和

const arr1 = [10, 20, 30];

const totalRes = arr1.reduce((total, value) => {
    return total + value;
}, 0);

console.log(total); // 60

eg3: 对象数组中的数值求和

const studentRes = [
  { subject: '数学', score: 60 },
  { subject: '物理', score: 70 },
  { subject: '化学', score: 80 },
];

const totalRes = studentRes.reduce((total, currentValue) => {
  return total + currentValue.score;
}, 0);

console.log(totalRes); // 210

eg4: 展平数组:将多维数组转换成一维.

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

const oneArr = twoArr.reduce((total, currentValue) => {
  return total.concat(currentValue);
});

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

eg5: 按属性分组对象

const scoreRes = [
  { subject: '物理', score: 41 },
  { subject: '化学', score: 59 },
  { subject: '数学', score: 36 },
  { subject: '英语', score: 90 },
  { subject: '生物', score: 64 },
];

let initialValue = {
  pass: [],
  fail: [],
};

const groupRes = scoreRes.reduce((total, currentValue) => {
  (currentValue.score >= 50) ? total.pass.push(currentValue) : total.fail.push(currentValue);
  return total;
}, initialValue);

console.log(groupRes);
// {
//   pass: [
//    { subject: '化学', marks: 59 },
//    { subject: '应用数学', marks: 90 },
//    { subject: '英语', marks: 64 }
//   ],
//   fail: [
//    { subject: '物理', marks: 41 },
//    { subject: '高等数学', marks: 36 }
//   ]
//  }

eg6: 删除数组中的重复项

const duplicatedsArr = [1, 5, 6, 5, 7, 1, 6, 8, 9, 7];

const removeDuplicatedArr = duplicatedsArr.reduce((accumulator, currentValue) => {
  if (!accumulator.includes(currentValue)) {
    accumulator.push(currentValue);
  }
  
  return accumulator;
}, []);

console.log(removeDuplicatedArr); // [ 1, 5, 6, 7, 8, 9 ]