finding duplicates in an 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: find-array-duplicates
npm i find-array-duplicates
import duplicates from 'find-array-duplicates'
const names = [
{ 'age': 36, 'name': 'Bob' },
{ 'age': 40, 'name': 'Harry' },
{ 'age': 1, 'name': 'Bob' }
]
duplicates(names, 'name').single()
Example 3: js find duplicates in array
[1, 2, 2, 4, 3, 4].filter((e, i, a) => a.indexOf(e) !== i)
Example 4: Find the duplicate in an array of N integers.
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int n=nums.size();
int s=nums[0];
int f=nums[nums[0]];
while(s!=f) {
s=nums[s];
f=nums[nums[f]];
}
f=0;
while(s!=f) {
s=nums[s];
f=nums[f];
}
return s;
}
};