Skip to content
☆´∀`☆
On this page

reduce 黑魔法,嘿嘿

reduce(callback(accumulator, currentValue[, index, array])[,initialValue]) reduce 接收两个参数:

  • callback(回调函数)
  • initialValue(初始值)[可选]

callback 接收四个参数:

  • accumulator 积累值
  • currentValue 当前值
  • **index **当前索引
  • **array **当前数值

应用场景: 可用于对数组进行提取,分组,等操作。

求和 & 乘法

javascript
const sum = [1, 2, 3].reduce((a, val) => {
  console.log(a, val);
  return a + val;
});
console.log(sum);

// 1 2
// 3 3
// 6

// 有初始值的情况
const sum = [1, 2, 3].reduce((a, val) => {
  console.log(a, val);
  return a + val;
}, 8);
console.log(sum);
// 8 1
// 9 2
// 11 3
// 14

连接不均匀数组

javascript
const str = [
  ["The", "red", "horse"],
  ["Plane", "over", "the", "ocean"],
  ["Chocolate", "ice", "cream", "is", "awesome"],
  ["this", "is", "a", "long", "sentence"],
].map(item => item.reduce((a, i) => `${a} ${i}`));
console.log(str);
// [
//   'The red horse',
//   'Plane over the ocean',
//   'Chocolate ice cream is awesome',
//   'this is a long sentence'
// ]

验证括号

javascript
[..."(())()(()())"].reduce((a, i) => (i === "(" ? a + 1 : a - 1), 0);
// 0

[..."((())()(()())"].reduce((a, i) => (i === "(" ? a + 1 : a - 1), 0);
// 1

[..."(())()(()()))"].reduce((a, i) => (i === "(" ? a + 1 : a - 1), 0);
// -1

根据属性值分组

javascript
const obj = [
  { name: "Alice", job: "Data Analyst", country: "AU" },
  { name: "Bob", job: "Pilot", country: "US" },
  { name: "Lewis", job: "Pilot", country: "US" },
  { name: "Karen", job: "Software Eng", country: "CA" },
  { name: "Jona", job: "Painter", country: "CA" },
  { name: "Jeremy", job: "Artist", country: "SP" },
];
const ppl = obj.reduce((group, val) => {
  let newkey = val["country"];
  if (!group[newkey]) {
    group[newkey] = [];
  }
  group[newkey].push(val);
  return group;
}, []);
console.log(ppl);
// [
//   AU: [ { name: 'Alice', job: 'Data Analyst', country: 'AU' } ],
//   US: [
//     { name: 'Bob', job: 'Pilot', country: 'US' },
//     { name: 'Lewis', job: 'Pilot', country: 'US' }
//   ],
//   CA: [
//     { name: 'Karen', job: 'Software Eng', country: 'CA' },
//     { name: 'Jona', job: 'Painter', country: 'CA' }
//   ],
//   SP: [ { name: 'Jeremy', job: 'Artist', country: 'SP' } ]
// ]

翻转字符串

javascript
const reverseStr = str => [...str].reduce((a, v) => v + a);