find all duplicates in javascript array code example
Example 1: js find duplicates in array
const names = ['Mike', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Nancy', 'Carl']
const count = names =>
names.reduce((a, b) => ({ ...a,
[b]: (a[b] || 0) + 1
}), {})
const duplicates = dict =>
Object.keys(dict).filter((a) => dict[a] > 1)
console.log(count(names))
console.log(duplicates(count(names)))
Example 2: javascript duplicate an array
let arr =["a","b","c"];
const duplicate = [...arr];
const duplicate = Array.from(arr);
Example 3: javascript get duplicates in array
function getDuplicateArrayElements(arr){
var sorted_arr = arr.slice().sort();
var results = [];
for (var i = 0; i < sorted_arr.length - 1; i++) {
if (sorted_arr[i + 1] === sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
return results;
}
var colors = ["red","orange","blue","green","red","blue"];
var duplicateColors= getDuplicateArrayElements(colors);
Example 4: find duplicate values in array javascript
const findDuplicates = (arr) => {
let sorted_arr = arr.slice().sort();
let results = [];
for (let i = 0; i < sorted_arr.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
return results;
}
let duplicatedArray = [9, 4, 111, 2, 3, 9, 4, 5, 7];
console.log(`The duplicates in ${duplicatedArray} are ${findDuplicates(duplicatedArray)}`);