equivalent in Groovy for Javascript's map()?

groovy, javascript, list, loops

Solution

You're probably looking for `collect`:

def numbers = [1,2,3]
assert numbers.collect { it * 2 } == [2,4,6]

There are also variants defined specifically for `Collection` and array types (as opposed to collect itself which is valid for any object, with the default behaviour treating an arbitrary object the same as a single-element array containing just that object), such as `collectMany`, which allows you to return a list of zero, one or more than one result for each element, with the results all concatenated

assert numbers.collectMany { (it > 1) ? [it, -1*it] : [] } == [2, -2, 3, -3]

Problem

In Javascript the function ``` array.map(callback[, thisArg]) ``` Creates a new array with the results of calling a provided function on every element in this array. (Per documentation on mdn). Is there something equivalent in Groovy?

Original source