Example 1: how to get duplicate values from array in javascript
var array = [1, 2, 2, 3, 3, 4, 5, 6, 2, 3, 7, 8, 5, 22, 1, 2, 511, 12, 50, 22];
console.log([...new Set(
array.filter((value, index, self) => self.indexOf(value) !== index))]
);
Example 2: count duplicates array js
uniqueCount = ["a","b","c","d","d","e","a","b","c","f","g","h","h","h","e","a"];
var count = {};
uniqueCount.forEach(function(i) { count[i] = (count[i]||0) + 1;});
console.log(count);
Example 3: find duplicates and their count in an array javascript
var counts = {};
your_array.forEach(function(x) { counts[x] = (counts[x] || 0)+1; });
Example 4: 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
}), {}) // 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' ]
Example 5: javascript duplicate an array
let arr =["a","b","c"];
// ES6 way
const duplicate = [...arr];
// older method
const duplicate = Array.from(arr);
Example 6: javascript find duplicate in array
// JavaScript - finds if there is duplicate in an array.
// Returns True or False.
const isThereADuplicate = function(arrayOfNumbers) {
// Create an empty associative array or hash.
// This is preferred,
let counts = {};
// // but this also works. Comment in below and comment out above if you want to try.
// let counts = [];
for(var i = 0; i <= arrayOfNumbers.length; i++) {
// As the arrayOfNumbers is being iterated through,
// the counts hash is being populated.
// Each value in the array becomes a key in the hash.
// The value assignment of 1, is there to complete the hash structure.
// Once the key exists, meaning there is a duplicate, return true.
// If there are no duplicates, the if block completes and returns false.
if(counts[arrayOfNumbers[i]] === undefined) {
counts[arrayOfNumbers[i]] = 1;
} else {
return true;
}
}
return false;
}