To eliminate duplicates using your current code, it is important to create a frequency map to store information about the duplicate elements. In this scenario, I have created a map using an object structure like this...
const freq = { 9: [9, 2], 1: [1, 1] ... };
In this setup, each iterated element serves as a key in the object, while the corresponding value includes the element itself and the number of duplicates. You can access these arrays by using Object.values
, then sort them based on the duplicate value with sort
, and finally iterate over the sorted nested array using map
to generate the final output.
However, please note that due to the sorting process, the resulting order will be [9, 1, 2, 6]
.
const source = [2, 9, 9, 1, 6];
// Apply `reduce` method on the array to create key/value pairs where
// the value is an array consisting of the element value and its duplicate count
const nested = source.reduce((acc, c) => {
// If the object property identified by the element
// value doesn't exist, assign an array to initialize
// the duplicate count as zero
acc[c] ??= [c, 0];
// Increase the duplicate count
++acc[c][1];
// Return the updated object for the next iteration
return acc;
}, {});
// Obtain the `Object.values` from the object (array of nested arrays)
// Sort them based on their duplicate count,
// Finally `map` over the sorted arrays to extract
// the first element from each
const out = Object.values(nested).sort((a, b) => {
return b[1] - a[1];
}).map(arr => arr[0]);
console.log(out);
For more information, please refer to: