I was given a challenge by a friend to find the duplicates in an array.
For instance, a function when it receives an array -
[1, 2, 3, 4, 5, 2, 2, 2]
should return the duplicated number 2
He challenged me to write the code without using more than 1 loop.
My first try
const findDuplicate = nums => {
const uniqueSet = []
let duplicate = null
nums.map(x => {
if(uniqueSet.includes(x)){
duplicate = x
}
uniqueSet.push(x)
})
return duplicate
}
so, findDuplicate([1, 2, 3, 4, 5, 2, 2, 2])
returns 2
He was not satisfied but wanted to try differently rather than looping it through.
After hours of breaking my head, I came up with this -
const findDuplicate = nums => {
const uniqueSet = new Set(nums)
const arrSum = nums.reduce((a, b) => a + b)
let uniqueArray = Array.from(uniqueSet)
const uniqueSetSum = uniqueArray.reduce((a, b) => a + b)
const duplicate = Math.abs(arrSum - uniqueSetSum) / (nums.length - uniqueArray.length)
return duplicate
}
He did not understand what is going on at the first look. After a while, he understood the code.
Which one do you prefer? Simpler code or Complex code? Or is there any other way you would solve this?
Share your thoughts. Thanks.
Top comments (3)
1loc.dev/
const countOccurrences = arr => arr.reduce((prev, curr) => (prev[curr] = ++prev[curr] || 1, prev), {});
// Examples
countOccurrences([2, 1, 3, 3, 2, 3]); // { '1': 1, '2': 2, '3': 3 }
countOccurrences(['a', 'b', 'a', 'c', 'a', 'b']); // { 'a': 3, 'b': 2, 'c': 1 }
This is good!
Do look at the other functions in 1loc.dev
I liked this trick: