数组对象中将相同的属性的对象分为一类,组合为一个新数组
arr = [
{ name: ‘a’, age: 1 },
{ name: ‘a’, age: 3 },
{ name: ‘b’, age: 2 },
{ name: ‘a’, age: 5 },
{ name: ‘b’, age: 4 },
{ name: ‘a’, age: 7 }
]
处理为:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/9bf2fde27bb5c946daa152a3af30b236.png)
// arr:要处理的数组 type:要归类的属性名
function classfyArr (arr, type) {
//将数组对象中属性的值归为一个数组
const a = arr.map((item) => {
return item[type]
})
const valueArr = [...new Set(a)]
//遍历push分类新数组
const newArr = []
valueArr.forEach(i => {
newArr.push(arr.filter(item => {
return item[type] === i
}))
})
console.log('newArr', newArr)
return newArr
}