利用reduce实现数组分类

const list = [
	  { type: 'shop', momey: 223 },
	  { type: 'study', momey: 341 },
	  { type: 'shop', momey: 821 },
	  { type: 'transfer', momey: 821 },
	  { type: 'study', momey: 821 }
	];
	const sortList = list.reduce((acc, cur) => {
	  // 如果不存在这个键,则设置它赋值 [] 空数组
	  if (!acc[cur.type]) {
	    acc[cur.type] = [];
	  }
	  acc[cur.type].push(cur)
	  return acc
	}, {})
	console.log(sortList) // {shop:[{ type: 'shop', momey: 223 },{ type: 'shop', momey: 821 }], study:[{ type: 'study', momey: 341 },{ type: 'study', momey: 821 }],transfer:[{ type: 'transfer', momey: 821 }]}

  

posted @ 2021-07-05 08:56  zaijinyang  阅读(134)  评论(0编辑  收藏  举报