您的位置:首页 > 博客中心 > 编程语言 >

利用reduce实现数组分类

时间:2022-03-29 01:55

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 }]}

  

本类排行

今日推荐

热门手游