xxxxxxxxxx
function hasDuplicates(array) {
return (new Set(array)).size !== array.length;
}
xxxxxxxxxx
function hasDuplicates(array) {
// create a set to store unique values
const uniqueValues = new Set();
// loop through the array
for (let i = 0; i < array.length; i++) {
// if the value is not in the set, add it
if (!uniqueValues.has(array[i])) {
uniqueValues.add(array[i]);
} else {
// if the value is already in the set, return true
return true;
}
}
// if the loop completes and there are no duplicates, return false
return false;
}
const numbers = [1, 2, 3, 4, 5];
const hasDuplicates = hasDuplicates(numbers); // returns false
const letters = ['a', 'b', 'c', 'b'];
const hasDuplicates = hasDuplicates(letters); // returns true
xxxxxxxxxx
[1, 2, 3].every((e, i, a) => a.indexOf(e) === i) // true
[1, 2, 1].every((e, i, a) => a.indexOf(e) === i) // false
xxxxxxxxxx
function checkIfDuplicateExists(w){
return new Set(w).size !== w.length
}
console.log(
checkIfDuplicateExists(["a", "b", "c", "a"])
// true
);
console.log(
checkIfDuplicateExists(["a", "b", "c"]))
//false
xxxxxxxxxx
function findUniq(arr) {
return arr.find(n => arr.indexOf(n) === arr.lastIndexOf(n));
}
console.log(findUniq([ 0, 1, 0 ]))
console.log(findUniq([ 1, 1, 1, 2, 1, 1 ]))
console.log(findUniq([ 3, 10, 3, 3, 3 ]))
console.log(findUniq([ 7, 7, 7, 20, 7, 7, 7 ]))
xxxxxxxxxx
const months = ['april','may','june','may','may','june'];
const countDuplicates = months.reduce((obj,month)=>{
if(obj[month] == undefined){
obj[month] = 1;
return obj;
}else{
obj[month]++;
return obj;
}
},{});
console.log(countDuplicates);//output:{april: 1, may: 3, june: 2}
xxxxxxxxxx
arr.reduce((b,c)=>((b[b.findIndex(d=>d.el===c)]||b[b.push({el:c,count:0})-1]).count++,b),[]);