assume i have an array of objects the following
const objects = [{ total: 2 }, { total: 5 }, { total: 1 }, { total: 8 },{ total: 2 },{ total: 3 },{ total: 8 },{ total: 1 },{ total: 2 }];
what would be the best way to calculate what is the total with most instances? it our case it would be 2 as it appears more than all the rest.
function findTotalWithMostInstances(arr) {
const frequency = arr.reduce((acc, obj) => {
const total = obj.total;
acc[total] = (acc[total] || 0) + 1;
return acc;
}, {});
let totalWithMostInstances;
let highestFrequency = 0;
for (const total in frequency) {
if (frequency[total] > highestFrequency) {
totalWithMostInstances = total;
highestFrequency = frequency[total];
}
}
return parseInt(totalWithMostInstances);
}
make it more efficient
2
Answers
There can be more than one total that occurs the same number of times. This would give you a list sorted from most instances to least:
Explanation: Reducing into an object working as a hash table with counters for each value of total. Using Object.entries to convert the object into an array of arrays. Sorting the array based on occurences.
You could reduce with a single loop and an object with additional max and values properties.
In each iteration increment the has and check if the count is greater than
max
, then get a new array forvalues
withtotal
as single item and incrementmax
. Ifmax
and count is equal, just addtotal
tovalues
.Finally return only
values
property.