Reputation: 1249
I have an array of objects that goes like:
test = {
bar: [
{p: '1',
v: '2',
sn: '1509007228'
},
{p: '34',
v: '3',
sn: '1509007228'
},
{p: '0.5',
v: '4',
sn: '1509007228'
}],
foo: [
{p: '1',
v: '2',
sn: '1509007228'
},
{p: '34',
v: '3',
sn: '1509007228'
},
{p: '0.5',
v: '4',
sn: '1509007228'
}]
}
And I found that function on SO that works like a charm... Even if I'm not sure exactly how since the reduce function is supposed to return an accumulator first and then the current value. I'm not sure how the accumulator is handled as it should return undefined
, but I guess that's a question for another place and time!
So here's the function (thanks to Tristan Reid):
Array.prototype.hasMin = function(attrib) {
return this.reduce(function(prev, curr){
return prev[attrib] < curr[attrib] ? prev : curr;
});
}
When I use it on the previous object it works perfectly:
var blu = test.foo.hasMin('p');
{ p: '0.5', v: '4', sn: '1509007228' }
And the result is correct if I reverse the logic: ie. trying to find the highest value:
Array.prototype.hasMin = function(attrib) {
return this.reduce(function(prev, curr) {
return prev[attrib] > curr[attrib] ? prev : curr;
});
};
I could call it then hasMax I guess... but you know, it's relatively irrelevant for now.
var blu = test.foo.hasMin('p');
{ p: '34', v: '3', sn: '1509007228' }
but when I try to use it on the actual object (much, much longer) it seems to stop on a specific value: 999.00
Here's the full object (I apologies for the size... I was unable to paste it here because of it (> 70,000 lines)).
And when I try the 'hasMax' function I get:
var bar = foo.bids.hasMin('p');
{ sn: '1509007228', v: '53.00000000', p: '999.00', type: 'bids' }
When the correct object for 'p'Max should be:
{
sn: '1509007228',
v: '0.15200000',
p: '5721.32',
type: 'bids'
},
I'm not sure if there's a limitation in the array.reduce
function that makes it impossible for this function to work on my object?
Anyhow, thanks in advance for your help!
Upvotes: 0
Views: 1310
Reputation: 1755
Please change your code that it looks like this:
return parseFloat(prev[attrib]) > parseFloat(curr[attrib]) ? prev : curr;
Your p is a string
p: '5721.32'
so you compare strings, when you should compare numbers.
Upvotes: 4