項目中往往會遇到對數(shù)組處理是否存在某個形同的值?;蛘邔ο笾惺欠翊嬖谛瓮亍?br> 下列方法常用,但不限于。
一、普通數(shù)組數(shù)據(jù)
1.1對數(shù)組進(jìn)行排序,對比上一個元素和下一個元素是否相等,若相等,則說明數(shù)組有重復(fù)值。
const arr=['111','222','333','444','555'];
//判斷數(shù)組元素是否有重復(fù)
var sarr = arr.sort();
for(let i=0; i<sarr.length; i++){
if(sarr[i] == sarr[i+1]){
alert("數(shù)組中重復(fù)元素是:" + sarr[i])
}
}
1.2:先將數(shù)組轉(zhuǎn)換成字符串,再遍歷數(shù)組,在字符串中移除當(dāng)前的數(shù)組元素之后還能找到該元素,則說明數(shù)組有重復(fù)值。
const arr=['111','111','333','444','555'];
var str = arr.join(",") + ",";
for(let i=0; i<arr.length; i++){
if(str.replace(arr[i]+",", "").indexOf(arr[i]+",") > -1){
alert("數(shù)組中重復(fù)元素是:" + arr[i]);
break
}
}
1.3先利用ES6語法將數(shù)組去重,之后再與原數(shù)組比較長度,若長度小于原數(shù)組,則說明數(shù)組有重復(fù)值。
Array.from(new Set(arr)).length < arr.length
//ES6去重方法
// 1. 拓展運(yùn)算符 + new Set方法
const arr=['111','222','333','444','555'];
let arr1 = [...new Set(arr)]
if(arr2.length < arr.length) {
console.log('有重復(fù)')
}else{
console.log('沒有重復(fù)')
}
// 2. Array.from + new Set方法
const arr=['111','111','333','444','555'];
let arr2 = Array.from(new Set(arr))
if(arr2.length < arr.length) {
console.log('有重復(fù)')
}else{
console.log('沒有重復(fù)')
}
二、對象元素數(shù)組
需求:要判斷下方這個數(shù)組中,name/age是否有重復(fù)的數(shù)據(jù).
2.1,先利用ES6語法Set將數(shù)組去重,之后再原數(shù)組比較長度,若長度小于原數(shù)組,則說明數(shù)組有重復(fù)值
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("重復(fù)");
}
2.2,先將數(shù)組轉(zhuǎn)換成字符串,再遍歷數(shù)組,在字符串中移除當(dāng)前的數(shù)組元素之后還能找到該元素,則說明數(shù)組有重復(fù)值。
const arr=[
{name:"張三3",age:12},
{name:"張三2",age:12},
{name:"張三",age:12},
{name:"張三1",age:12}
];
/*
replace不用正則的話,只會替換掉第一個符合條件的數(shù)據(jù)
之所以加逗號,是因為這樣可以確保數(shù)據(jù)的唯一性,如果不加逗號,會導(dǎo)致數(shù)據(jù)不對,比如說第三條數(shù)據(jù)"張三",replace之后還會查到第四條數(shù)據(jù)中的"張三",所以得加上逗號確保唯一性
*/
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("重復(fù)");
}
2.3,利用findIndex或者indexOf查到的下標(biāo)和當(dāng)前循環(huán)的下標(biāo)對比是否相等
//indexOf查找是否有重復(fù)的
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("重復(fù)");
}
文章來源:http://www.zghlxwxcb.cn/news/detail-702193.html
//findIndex查找是否有重復(fù)的
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("重復(fù)");
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-702193.html
到了這里,關(guān)于js判斷一個數(shù)組中是否有重復(fù)的數(shù)組/ 一個數(shù)組中對象的某個屬性值是否重復(fù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!