Node.js lodash min/max get min/max object attribute value

Description

Node.js lodash min/max get min/max object attribute value


var _ = require('lodash');

var people = [//from  w  w w . j av a 2s .  c om
  { id: 1, name: "Jim", age: 20, gender: 'm', enabled: true },
  { id: 1, name: "Jim", age: 20, gender: 'm', enabled: false },  
  { id: 2, name: "Bob", age: 34, gender: 'm', enabled: true },
  { id: 3, name: "Steve", age: 30, gender: 'm', enabled: true },
  { id: 4, name: "Nancy", age: 42, gender: 'f', enabled: true },
  { id: 5, name: "Frank", age: 30, gender: 'm', enabled: true },
  { id: 6, name: "Larry", age: 68, gender: 'm', enabled: true },
  { id: 7, name: "Larry Jr", age: 28, gender: 'm', enabled: true },
  { id: 8, name: "Sally", age: 24, gender: 'f', enabled: true },
  { id: 9, name: "Wanda", age: 22, gender: 'f', enabled: true },
  { id: 10, name: "John", age: 24, gender: 'm', enabled: true },
  { id: 11, name: "Bill", age: 24, gender: 'm', enabled: true },
  { id: 12, name: "Kelly", age: 25, gender: 'f', enabled: true },
  { id: 13, name: "Donna", age: 26, gender: 'f', enabled: true }
];

// get the min and max age values

var ages = _.map(people,'age');

var minAge = _.min(ages);
console.log(minAge);

var maxAge = _.max(ages);
console.log(maxAge);

// get the youngest and oldest people

var youngest = _.minBy(people, 'age');
console.log(youngest);

var oldest = _.maxBy(people, 'age');
console.log(oldest);

More example

var lodash = require('lodash');
console.log(lodash.min([1,2,3,4,5,2,2,4,0]));

console.log(lodash.max([4, 2, 8, 6]));/*from  w ww.j  a  v  a  2 s  .co m*/
//  8

console.log(lodash.max([]));
//  -Infinity

var users = [
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 }
];

console.log(lodash.max(users, function(chr) {
  return chr.age;
}));
//  { 'user': 'fred', 'age': 40 }

// using the `_.property` callback shorthand
console.log(lodash.max(users, 'age'));
//  { 'user': 'fred', 'age': 40 }



PreviousNext

Related