Home > Back-end >  I am learning .map.. but I am having trouble with this problem
I am learning .map.. but I am having trouble with this problem

Time:05-17

The Problem...

Rewrite the example below using .map instead of a for-loop.

let selectedMonths = [
    { name: 'January', revenue: 10, expenses: 5, quarter: 1 },
    { name: 'February', revenue: 7, expenses: 8, quarter: 1 },
    { name: 'March', revenue: 15, expenses: 3, quarter: 1 }
]

let monthlyProfitLabels = []
for(let i = 0; i < selectedMonths.length; i  ){
    let month = selectedMonths[I]
    let label = `${month.name}: ${month.revenue - month.expenses}`
    monthlyProfitLabels.push(label)
}

console.log(monthlyProfitLabels)

What they gave me to type in*

let selectedMonths = [
    { name: 'January', revenue: 10, expenses: 5, quarter: 1 },
    { name: 'February', revenue: 7, expenses: 8, quarter: 1 },
    { name: 'March', revenue: 15, expenses: 3, quarter: 1 } 
]

let monthlyProfitLabels = null; // <-- replace null

console.log(monthlyProfitLabels);

What I typed so far...

let monthlyProfitLabels = selectedMonths.map(function(month){
  let label = `${month.name}: ${month.revenue - month.expenses}`
    monthlyProfitLabels.push(label) 
})

console.log(monthlyProfitLabels);

It is telling me "Can't access uninitialized variable".. I'm so confused... the backticks are there before $ and after } for label but they aren't showing on here.

CodePudding user response:

map (spec | MDN) - creates a new array from the values returned by the callback

let selectedMonths = [
    { name: 'January', revenue: 10, expenses: 5, quarter: 1 },
    { name: 'February', revenue: 7, expenses: 8, quarter: 1 },
    { name: 'March', revenue: 15, expenses: 3, quarter: 1 } 
]
let monthlyProfitLabels = selectedMonths.map(function(month){
  let label = `${month.name}: ${month.revenue - month.expenses}`
  return label
})

You need return elements for monthlyProfitLabels

CodePudding user response:

Observation : Array.map() creates a new array populated with the results of calling a provided function on every element in the calling array. Hence, no need to do this unwanted code execution monthlyProfitLabels.push(label). You have to simply return the label.

Demo :

let selectedMonths = [
    { name: 'January', revenue: 10, expenses: 5, quarter: 1 },
    { name: 'February', revenue: 7, expenses: 8, quarter: 1 },
    { name: 'March', revenue: 15, expenses: 3, quarter: 1 }
];

let monthlyProfitLabels = selectedMonths.map(function(month){
  let label = `${month.name}: ${month.revenue - month.expenses}`
    return label; 
});

console.log(monthlyProfitLabels);

  • Related