In CoffeeScript how do you append a value to an Array?

ArraysAppendCoffeescript

Arrays Problem Overview


What is the prescribed way to append a value to an Array in CoffeeScript? I've checked the PragProg CoffeeScript book but it only discusses creating, slicing and splicing, and iterating, but not appending.

Arrays Solutions


Solution 1 - Arrays

Good old push still works.

x = []
x.push 'a'

Solution 2 - Arrays

Far better is to use list comprehensions.

For instance rather than this:

things = []
for x in list
  things.push x.color

do this instead:

things = (x.color for x in list)

Solution 3 - Arrays

If you are chaining calls then you want the append to return the array rather than it's length. In this case you can use .concat([newElement])

Has to be [newElement] as concat is expecting an array like the one its concatenating to. Not efficient but looks cool in the right setting.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDave SagView Question on Stackoverflow
Solution 1 - ArraysThiloView Answer on Stackoverflow
Solution 2 - ArrayssuranyamiView Answer on Stackoverflow
Solution 3 - ArraysPaul SchoolingView Answer on Stackoverflow