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
.
Thanks.
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.
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.
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;});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With