Input : ['A', 'B', 'C', 'A', 'D', 'B', 'B', 'A', 'D']
Expected output : 'B'
The output should be the element with higher occurrence. If there are two or more elements which shares the same number of occurrence, then the element which reaches the maximum count earlier in the array should be the expected output. In the above case, 'B' and 'A' has count of 3. Since 'B' reaches the max count earlier than 'A', 'B' should be the output.
I have already found the solution for this.
My Solution
let input = ['A', 'B', 'C', 'A', 'D', 'B', 'B', 'A', 'D']
const findWinner = (arr) => {
const reduced = arr.reduce((acc, value) => ({ ...acc,
[value]: (acc[value] || 0) + 1
}), {})
let pickLargest = Object.entries(reduced)
const winner = pickLargest.reduce((acc, [key, value]) => {
if (value > acc.maxValue) {
acc.maxValue = value
acc.winner = key
} else if (value == acc.maxValue) {
if (arr.lastIndexOf(key) > arr.lastIndexOf(acc.winner)) {
acc.winner = acc.winner
} else {
acc.winner = key
}
}
return acc
}, {
maxValue: 0,
winner: ''
})
return winner.winner
}
console.log(findWinner(input));
Is there any other elegant way to achieve the same result?
You could take an object for keeping track of the counts and adjust max, if necessary.
const
findWinner = array => {
const counts = {};
let max;
for (const value of array) {
counts[value] = (counts[value] || 0) + 1;
if (counts[value] <= counts[max]) continue;
max = value;
}
return max;
};
console.log(findWinner(['A', 'B', 'C', 'A', 'D', 'B', 'B', 'A', 'D']));