Reputation: 9759
How can I find the max cell value in a collection of objects using lodash while ignoring one of the keys.
var data = [{
tick: 0,
valueA: 3,
valueB: 2
}, {
tick: 6,
valueA: 6,
valueB: 3
}, {
tick: 12,
valueA: 2,
valueB: 4
}, ...];
I want to find the max tick, this is the row identifier, and the max of all other values. What I have so far is:
var maxTick = _.max(data, 'tick'),
maxValue = _.max(data, function(o) { return _.max(_.values(o))};);
How can I let maxValue
ignore the tick data?
Upvotes: 0
Views: 484
Reputation: 4129
You just need a function which iterates through all elements properties and a list of ignored properties. Here is a sample:
var findMax = function(list, ignoredFields){
var maxValue = null;
for(var i=0;i<list.length;i++){
for(var prop in list[i]){
if(ignoredFields.indexOf(prop) < 0){
maxValue = maxValue < list[i][prop] ? list[i][prop] : maxValue;
}
}
}
return maxValue;
}
And you execute the function with your data and the list of ignored properties
findMax(data,['tick'])
Update: modified the function to use lodash iterations
var findMax = function(list, ignoredFields){
var maxValue = null;
_.forEach(list, function(element, index) {
var _localMax = _.max(_.omit(element, ignoredFields));
maxValue = maxValue < _localMax ? _localMax : maxValue;
});
return maxValue;
}
Upvotes: 1
Reputation: 3415
Try using _.pick() to pick out all keys except tick then run your max function on that new collection. By the way, your maxValue function doesn't seem right. Are you saying that you want to take the highest scalar valuer in any object, or the object which contains the highest scalar value (except tick)?
UPDATE: Based on your response, try this: http://jsfiddle.net/tonicboy/Xxf9E/1/
var data = [{
tick: 0,
valueA: 3,
valueB: 2
}, {
tick: 6,
valueA: 6,
valueB: 3
}, {
tick: 12,
valueA: 2,
valueB: 4
}],
data2 = [];
_.each(data, function(element, index) {
var values = _.values(_.omit(element, 'tick'));
data2 = data2.concat(values);
});
console.log(data2);
console.log(_.max(data2));
Upvotes: 0
Reputation: 2103
Along T Nguyen's line of thought but use _.omit
instead of pick that way you only have to omit tick
_.max(data, function(o){_.omit(o, "tick")})
Upvotes: 4