Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript maps an array


May 09, 2021 CoffeeScript


Table of contents


Map the array

Problem

You have an array of objects that you want to map to another array, just like Ruby maps.

Solution

Use map() and anonymous functions, but don't forget that there are list inferences.

electric_mayhem = [ { name: "Doctor Teeth", instrument: "piano" },
                    { name: "Janice", instrument: "lead guitar" },
                    { name: "Sgt. Floyd Pepper", instrument: "bass" },
                    { name: "Zoot", instrument: "sax" },
                    { name: "Lips", instrument: "trumpet" },
                    { name: "Animal", instrument: "drums" } ]

names = electric_mayhem.map (muppet) -> muppet.name
# => [ 'Doctor Teeth', 'Janice', 'Sgt. Floyd Pepper', 'Zoot', 'Lips', 'Animal' ]

Discuss

Because CoffeeScript supports anonymous functions, mapping arrays in CoffeeScript is as simple as it is in Ruby. M apping in CoffeeScript is a great way to handle complex transformations and embellishment mapping. If your transformation is as simple as the one in the example above, you might think of it as a list inference (http://coffeescript-cookbook.github.io/chapters/arrays/list-comprehensions) that looks a little clearer.