例如有需求,要判断下方这个数组中,name是否有重复的数据
const arr=[
{name:"张三3",age:12},
{name:"张三2",age:12},
{name:"张三",age:12},
{name:"张三1",age:12}
];
下面用三种方法解决
- 先利用ES6语法Set将数组去重,之后再原数组比较长度,若长度小于原数组,则说明数组有重复值
const arr=[
{name:"张三3",age:12},
{name:"张三2",age:12},
{name:"张三",age:12},
{name:"张三1",age:12}
];
const newListLength=new Set(arr.map(item=>item.name)).size;
const listLength=arr.length;
if(listLength>newListLength){
console.log("重复");
}
- 先将数组转换成字符串,再遍历数组,在字符串中移除当前的数组元素之后还能找到该元素,则说明数组有重复值。
const arr=[
{name:"张三3",age:12},
{name:"张三2",age:12},
{name:"张三",age:12},
{name:"张三1",age:12}
];
/*
replace不用正则的话,只会替换掉第一个符合条件的数据
之所以加逗号,是因为这样可以确保数据的唯一性,如果不加逗号,会导致数据不对,比如说第三条数据"张三",replace之后还会查到第四条数据中的"张三",所以得加上逗号确保唯一性
*/
const newArr=arr.map(item=>item.name);
const str=newArr.join(",")+",";
const flag=newArr.some(item=>{
return str.replace(item+",","").indexOf(item+",")>-1
});
if(flag){
console.log("重复");
}
- 利用findIndex或者indexOf查到的下标和当前循环的下标对比是否相等
//indexOf查找是否有重复的
const arr=[
{name:"张三3",age:12},
{name:"张三2",age:12},
{name:"张三",age:12},
{name:"张三1",age:12}
];
const newArr=arr.map(item=>item.name);
const isRepeat=newArr.some((item,index,arr)=>arr.indexOf(item)!=index);
if(isRepeat){
console.log("重复");
}
//findIndex查找是否有重复的
const arr=[
{name:"张三3",age:12},
{name:"张三2",age:12},
{name:"张三",age:12},
{name:"张三1",age:12}
];
const newArr=arr.map(item=>item.name);
const isRepeat=newArr.some((x,index,arr)=>arr.findIndex(y=>y==x)!=index);
if(isRepeat){
console.log("重复");
}