Javascript数组方法:reduce的高级用法

reduce 是 JavaScript 中数组的高阶函数之一,它可以将数组中的所有元素累加到一个单独的值中。下面是一些 reduce 的高级用法:

1、将数组按属性分组

const arr = [
  { name: 'apple', type: 'fruit', color: 'red' },
  { name: 'banana', type: 'fruit', color: 'yellow' },
  { name: 'carrot', type: 'vegetable', color: 'orange' },
  { name: 'broccoli', type: 'vegetable', color: 'green' },
];

const result = arr.reduce((acc, cur) => {
  (acc[cur.type] = acc[cur.type] || []).push(cur);
  return acc;
}, {});

console.log(result);
/* 
{ 
	fruit: [ 
		{ name: 'apple', type: 'fruit', color: 'red' }, 
		{ name: 'banana', type: 'fruit', color: 'yellow' } 
	], 
	vegetable: [ 
		{ name: 'carrot', type: 'vegetable', color: 'orange' }, 
		{ name: 'broccoli', type: 'vegetable', color: 'green' } 
	]
}
*/

2、将二维数组转化为一维数组

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

const result = arr.reduce((acc, cur) => [...acc, ...cur], []);

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

3、计算数组中每个元素出现的次数

const arr = ['apple', 'banana', 'apple', 'carrot', 'banana', 'carrot', 'apple'];

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

console.log(result); // { apple: 3, banana: 2, carrot: 2 }

4、根据条件过滤数组

const arr = [
  { name: 'apple', type: 'fruit', color: 'red' },
  { name: 'banana', type: 'fruit', color: 'yellow' },
  { name: 'carrot', type: 'vegetable', color: 'orange' },
  { name: 'broccoli', type: 'vegetable', color: 'green' },
];

const result = arr.reduce((acc, cur) => {
  if (cur.color === 'red' || cur.color === 'green') {
    acc.push(cur);
  }
  return acc;
}, []);

console.log(result);
/*
	[ 
		{ name: 'apple', type: 'fruit', color: 'red' },
		{ name: 'broccoli', type: 'vegetable', color: 'green' } 
	]
*/

你可能感兴趣的:(javascript,前端,vue.js)