Friday, May 17, 2024
2
rated 0 times [  3] [ 1]  / answers: 1 / hits: 37450  / 11 Years ago, sat, april 6, 2013, 12:00:00

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.


More From » underscore.js

 Answers
1

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;});

[#79083] Friday, April 5, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jelani

Total Points: 473
Total Questions: 99
Total Answers: 99

Location: Cape Verde
Member since Fri, Nov 27, 2020
4 Years ago
;