You could remove the need for your xAxis
variable through using the index when mapping:
vm.pnLreportingPlotData.push(plotModel.map(function (o, i) {
return { x: i + 1, y: o.PnLreporting }
}
vm.var95Plotdata.push(plotModel.map(function (o, i) {
return { x: i + 1, y: o.VaR95Total }
}
vm.var99PlotData.push(plotModel.map(function (o, i) {
return { x: i + 1, y: o.VaR99Total }
}
Array.prototype.map provides three arguments, currentValue
(o
), index
, and array
(which isn't needed in our example)
N.B. you did not need to keep declaring xAxis
after you had done so the first time (no need for the multiple var
declarations, they could simply become xAxis = 1
)
While the above answers your question of how to avoid redeclaring xAxis
, I've added a few additional comments below:
Naming
You could possibly benefit from using more descriptive variable names. It is not immediately obvious what variables such as o
represent. Likewise, i
could be changed to index
if you found it helped readability.
Consistency:
var95Plotdata
uses lowercase 'd' for 'data', however var99PlotData
capitializes it (is this a typo?)
VaR95Total
capitalizes both 'V' and 'R' - can this be changed to be consistent with your view model or is this coming from an external api?
Extracting logic
Since the logic is almost identical besides property names, you could extract the logic if you wanted:
function getPlotData(property) {
// Ideally renaming `o` to whatever it represents
return plotModel.map(function (o, index) {
return { x: index + 1, y: o[property] }
}))
}
vm.pnLreportingPlotData.push(getPlotData('PnLreporting'))
vm.var95Plotdata.push(getPlotData('vaR95Total'))
vm.var99PlotData.push(getPlotData('VaR99Total'))