How to map an array in Coffeescript ?

Array in CoffeeScript: Coffeescript array and array object is very similar to JavaScript array and object of array, objects may be created using curly braces or may not be its depends on programmer choice.

Example of Array: 

name = ["sarthak","surabhi", "tejal",
        "dipali", "girija", "devendra"] 

department = {
   id : 10,
   branch : "computer"
}

skills = 
    designer :
         name : "ali"
         surname : "bazzi"
   backend :
         name : "sunny"
          surname : "warner"

Map array in CoffeeScript: Array map() is used when we want to transformed each value of the array and want to get new array out of it. The map is just used to map or track the value of the array

Example 1: In the below example we have an array of objects with different values in form of key-value pair and we apply the map function on that array to get a specific object’s value. In short, we want to transform an array to get a new array out of it. 

Javascript




engineers = [
  { name : "ali" , surname : "bazzi"},
  { name : "virat" , surname : "sharma"},
  { name : "sharma" , surname : "pandey"},
  { name : "paresh" , surname : "vikramadity"},
  { name : "sandip" , surname : "jain"}
]
   
names_record = engineers.map(firstname) -> firstname.name
console.log(names_record)


Output:

['ali', 'virat', 'sharma', 'paresh', 'sandip'] 

Example 2: In this example, we will perform some extra additional operations on the array using the map.

Javascript




numbers = [2 , 3, 5, 6, 4, 7]
 
double_numbers = numbers.map(num) -> return num * 2
 
console.log(double_numbers)


Output:

[4, 6, 10, 12, 8, 14]

In the above example, we map the numbers array by multiplying each value of the array by 2.

Reference: https://coffeescript-cookbook.github.io/chapters/arrays/mapping-arrays

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button