Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

underscore to find min and max of object value

As per the tutorial here,

A collection can either be an array or an object, an associate array in JavaScript

does that mean all the functions under collection is equally applicable to object literals. For example, I wanted to pick the values based on a condition. Say,

var obj = {
"1": {id: 1, val: 2},
"2": {id: 2, val: 5},
"3": {id: 3, val: 8},
"4": {id: 4, val: 1}
}

I want to find max and min of val field. Looking at the API, I was thinking to use pluck to get an array of val, then do min and max.

  • can I apply pluck to object (as the api example show the use in an array of objects)
  • is there a better way?

Thanks.

like image 895
bsr Avatar asked Apr 06 '13 13:04

bsr


People also ask

How do you find the maximum and minimum of an array of objects?

Using map(), Math, and the spread operator map() function, we take all of our Y values and insert them into a new Array of Numbers. Now that we have a simple Array of numbers, we use Math. min() or Math. max() to return the min/max values from our new Y value array.

What is underscore min JS?

Underscore. JS is a popular javascript based library which provides 100+ functions to facilitate web development. It provides helper functions like map, filter, invoke as well as function binding, javascript templating, deep equality checks, creating indexes and so on.


1 Answers

does that mean all the functions under collection is equally applicable to object literals?

Yes.

can I apply pluck to object (as the api example show the use in an array of objects)

Have you tried it? Yes, you can, but you will get back an array.

is there a better way?

Math.min.apply(null, _.pluck(obj, "val")) (or _.min(_.pluck(obj, "val"))) for getting the minimum value is fine. Yet, if you wanted to get the whole object (with id) you might also use the iterator parameter of min/max:

var lowest = _.min(obj, function(o){return o.val;});
like image 96
Bergi Avatar answered Oct 19 '22 01:10

Bergi