AnnanFay
AnnanFay

Reputation: 9759

Get maximum attributes from list of objects using lodash?

I have a list of objects:

var objects = [
    {name: 'Fred', age: 63, height: 12},
    {name: 'Jane', age: 32, height: 32},
    {name: 'Dune', age: 12, height: 555}
];

I want to work out what all the maximum attributes are:

var maximums = magic(objects);
// {name: 'Jane', age: 63, height: 555}

Is there any easy way to do this? Without manually looping.

Upvotes: 2

Views: 657

Answers (2)

Ori Drori
Ori Drori

Reputation: 192287

You can _.merge() the objects in a reduce loop (lodash or ES5), and use the customizer function of the merge to take the props with the maximum value on each iteration.

var objects = [
    {name: 'Fred', age: 63, height: 12},
    {name: 'Jane', age: 32, height: 32},
    {name: 'Dune', age: 12, height: 555}
];

var maximums = _(objects).reduce(function(obj, item) {
  return _.merge(obj, item, function(a, b) {
    return a > b ? a : b;
  });
}, {});

document.write(JSON.stringify(maximums));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>

Upvotes: 1

RobG
RobG

Reputation: 147453

I can't see how you can do this without some kind of iteration or loop: firstly over the objects array and secondly over the properties of each object to get the maximum value.

There are native methods to get this done since ES5, though if performance matters, plain loops tend to be faster (and not much more code).

var objects = [
    {name: 'Fred', age: 63, height: 12},
    {name: 'Jane', age: 32, height: 32},
    {name: 'Dune', age: 12, height: 555}
];

var maxes = objects.reduce(function(acc, obj) {
  Object.keys(obj).forEach(function(key) {
    acc[key] = acc[key] > obj[key]? acc[key] : obj[key];
  });
  return acc;
},{});

document.write(JSON.stringify(maxes));

Upvotes: 0

Related Questions