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
let arr = [1, 2, 3, 4, 5, 5];
const seen = new Set();
const duplicates = arr.filter(n => seen.size === seen.add(n).size);
console.log(duplicates); // [ 5 ]
console.log(duplicates.length); // 1
xxxxxxxxxx
const counts = {};
const sampleArray = ["1", "5", "9", "14", "5", "22", "48", "25", "22", "20", "9" ,"13"]
sampleArray.forEach(function (x) { counts[x] = (counts[x] || 0) + 1; });
console.log(counts)
// output: {
'1': 1,
'5': 2,
'9': 2,
'13': 1,
'14': 1,
'20': 1,
'22': 2,
'25': 1,
'48': 1
}
xxxxxxxxxx
function findDuplicates(arr) {
let seen = {};
let duplicates = [];
for (let i = 0; i < arr.length; i++) {
if (seen[arr[i]]) {
duplicates.push(arr[i]);
} else {
seen[arr[i]] = true;
}
}
return duplicates;
}
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
var input = [1, 2, 3, 1, 3, 1];
var duplicates = input.reduce(function(acc, el, i, arr) {
if (arr.indexOf(el) !== i && acc.indexOf(el) < 0) acc.push(el); return acc;
}, []);
document.write(duplicates); // = 1,3 (actual array == [1, 3])
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
const names = ['Mike', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Nancy', 'Carl']
const count = names =>
names.reduce((a, b) => ({ a,
[b]: (a[b] || 0) + 1
}), {}) // don't forget to initialize the accumulator
const duplicates = dict =>
Object.keys(dict).filter((a) => dict[a] > 1)
console.log(count(names)) // { Mike: 1, Matt: 1, Nancy: 2, Adam: 1, Jenny: 1, Carl: 1 }
console.log(duplicates(count(names))) // [ 'Nancy' ]
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 arr = ["q", "w", "w", "e", "i", "u", "r"]
arr.reduce((acc, cur) => {
if(acc[cur]) {
acc.duplicates.push(cur)
} else {
acc[cur] = true //anything could go here
}
}, { duplicates: [] })