// 对于数组对象中,查询出name属性值相同的元素
let obj = [
{
name:"幼儿园",
num:100,
level:1
},
{
name:"幼儿园1",
num:10,
level:3
},
{
name:"幼儿园3",
num:110,
level:3
},
{
name:"幼儿园1",
num:101,
level:2
},
{
name:"幼儿园",
num:100,
level:1
},
{
name:"幼儿园4",
num:10,
level:3
},
{
name:"幼儿园",
num:110,
level:3
},
{
name:"幼儿园5",
num:101,
level:2
},
{
name:"幼儿园3",
num:110,
level:3
},
{
name:"幼儿园5",
num:101,
level:2
}
]
//利用对象的唯一性
// 1.用for+变量
let obj2 ={};
for (let i = 0; i < obj.length; i++) {
if(!obj2[obj[i].name]){
obj2[obj[i].name] = [];
obj2[obj[i].name].push(obj[i]);
}else{
obj2[obj[i].name].push(obj[i]);
}
}
console.log(obj2);
// 2.reduce()
let objs = obj.reduce((total, currentValue,)=>{
if(!total[currentValue.name]){
total[currentValue.name] = []
total[currentValue.name].push(currentValue)
}else{
total[currentValue.name].push(currentValue)
}
return total;
},{})
console.log(objs);
// 在去重的基础上再进行获取重复元素
let newArr=[],uniArr=[];
for (let i = 0; i < obj.length; i++) {
let name = obj[i].name;
if(!uniArr.includes(name)){
uniArr.push(name);
newArr[uniArr.length-1] = [];
newArr[uniArr.length-1].push(obj[i]);
}else{
let index =uniArr.indexOf(name)>-1?uniArr.indexOf(name):0;
newArr[index].push(obj[i]);
}
}
console.log(newArr,uniArr);
1***@qq.com
- 发布:2022-11-15 16:15
- 更新:2022-11-15 16:15
- 阅读:312
0 个评论
要回复文章请先登录或注册