Reputation: 8899
I am trying to check duplicate in the following array, just i am want to return true or false if duplicate exists.
var array = ["Saturday", "Sunday", "Monday", "Tuesday", "Saturday" ];
for ( var i = 0; i < array.length; i++){
for (var j = i+1; j< array.length; j++){
if (array [i] === array [j]){
console.log(array[i]);
}
}
}
I tried the above , it giving result only for one item in an array not for comma separated. How i can write a duplicate check function in best way for comma separated array?
Array(10)
0: "test3,tier 1,test,test2
"1: "test3,tier 1,test,test2
"2: "test3,tier 1,test,test2
"3: "test3,tier 1,test,test2
"4: "test3,tier 1,test,test2
"5: "test3,tier 1,test,test2
"6: "test3,tier 1,test,test2
"7: "test3,tier 1,test,test2
"8: "test3,tier 1,test,test2
"9: "test3,tier 1,test,test2
"length: 10
__proto__: Array(0)
Upvotes: 0
Views: 1509
Reputation: 379
The items in a Set
will always be unique, as it only keeps one copy of each value you put in. Here's a function that uses this property:
function hasDuplicates(iterable) {
return new Set(iterable).size !== iterable.length;
}
// Demo
var array = ["Saturday", "Sunday", "Monday", "Tuesday", "Saturday" ];
console.log(hasDuplicates(array))
// Returns True if there is duplicates
// Otherwise return false
Set(iterable).size
will return the count of unique elements in that set, while iterable.length
is the counts of all elements in the original array.
Edit #1
To check ONLY the first item for duplicates you can use something like this
var array = ["Saturday", "Saturday", "Sunday", "Monday", "Tuesday" ];
console.log(array.indexOf(array[0] , 1) === -1 ? "No duplicates" : "Has duplicate" );
Upvotes: 3
Reputation: 8899
// Check duplicates in upload data excel
checkDuplicates(arr) {
if (arr.length > 1) {
for (var i = 0; i < arr.length; i++) {
for (var j = i + 1; j < arr.length; j++) {
if (arr[i].split(',')[0] === arr[j].split(',')[0]) {
return true;
} else {
return false;
}
}
}
} else {
return false;
}
}
Upvotes: 0