Javascript equivalent of Ruby's array.collect(&:method)

Updated . Posted . Visible to the public.

The most common use case for Ruby's #collect is to call a method on each list element and collect the return values in a new array:

['hello', 'world', 'this', 'is', 'nice'].collect(&:length)
# => [5, 5, 4, 2, 4]

Although there is no equivalent to this idiom in naked Javascript, there is a way to collect object properties (but not method results) if you are using common Javascript libraries.

If you are using jQuery with the Underscore.js Show archive.org snapshot utility library, you can use pluck Show archive.org snapshot :

_(['hello', 'world', 'this', 'is', 'nice']).pluck('length');
// -> [5, 5, 4, 2, 4]

If you are using the Prototype Show archive.org snapshot framework, there is also a method called pluck Show archive.org snapshot :

['hello', 'world', 'this', 'is', 'nice'].pluck('length');
// -> [5, 5, 4, 2, 4]
Henning Koch
Last edit
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2011-10-20 15:02)