Read more

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

Henning Koch
October 20, 2011Software engineer at makandra GmbH

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]
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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]
Posted by Henning Koch to makandra dev (2011-10-20 17:02)