Return a list of non-unique entries in a primitive (number) array in JavaScript
A fun little challenge, try to do it as little code as possible!
Just a fun little challenge I made for myself when figuring out a wider solution for something I am working on. I thought id put it out there for others. Since it's javaScript there is far more than one way to do it!
Ignoring good code style and other things like optimization, I have, (so far) come up with two solutions myself, which appear to work, but I'd love to see your solutions, paste them in the comments. Try and make them shorter than the shortest here or in the comments!
Rules are: Just keep it short as possible, don't need to worry about optimization or anything!
/*
* Given the array, create a function that returns the NON unique elements of the array.
* For example: with array [1, 2, 2, 4, 3, 4] the function should return [3,4] as they are the only non-unique numbers
*/
// My 2 solutions
const nums = [1, 2, 2, 4, 3, 4]
const getNonUniqueValues = arr =>
Object.entries(arr.reduce((a,v) =>
(a[v] ? a[v] += 1 : a[v] = 1) && a,{}))
.map(([k,v]) => (v > 1 && k[0]) && (~~k[0])).filter(u => u)
const getNonUniqueValues2 = arr =>
[...new Set(arr.sort().join('').match(/(\d)\1/g).join(''))].map(Number)
console.log(getNonUniqueValues(nums)) // [2,4]
console.log(getNonUniqueValues2(nums)) // [2,4]
Have fun!