Say, I have the following array:
[
{a:1, b:"apples"},
{a:3, b:"apples"},
{a:4, b:"apples"},
{a:1, b:"bananas"},
{a:3, b:"bananas"},
{a:5, b:"bananas"},
{a:6, b:"bananas"},
{a:3, b:"oranges"},
{a:5, b:"oranges"},
{a:6, b:"oranges"},
{a:10, b:"oranges"}
]
I want to efficiëntly get for each type of 'b' the whole object with the highest a, so my function should produce:
[
{a:4, b:"apples"},
{a:6, b:"bananas"},
{a:10, b:"oranges"}
]
Now I would do something like this:
var cache = {};
var resultobj = {};
result = [];
array.forEach(function (r) {
if (cache[r.b] && cache[r.b] > r.a) {
result[r.b] = r;
}
})
for (var key in result) {
result.push(result[key]);
}
That looks terrible inefficiënt...?