1

I want to use the same function to calculate a different array inside an object. so how can I get access to a specific array? example like year2018.salary thanks

    init();
var year2019 = {
    year: 2019,
    salary: [9087, 10590, 9549, 10481, 9410, 9656, 12551, 10038, 9183, 8490, 9263, 9089]
}

var year2018 = {
    year: 2018,
    salary: [9274, 9674, 9775, 11000, 11005, 9320, 12111, 9828, 9342, 9725, 9315, 9408],
    insurance: [362, 393, 402, 519, 500, 365, 588, 406, 387, 398, 366, 372],
    healthFees: [426, 449, 454, 538, 524, 429, 587, 457, 444, 452, 428, 434],

}
function averageCalc(year) {
    sumTotal = 0;
    currentYear = 'year' + year;    
       for (var i = 0; i < currentYear.salary.length; i++) {
           sumTotal += currentYear.salary[i];
       }
        console.log('The total salary in ' + year + ' is ' + sumTotal);
        console.log(currentYear);
    }    

averageCalc(2018);
function init() {
    var sumTotal, currentYear;

}
Yosef
  • 33
  • 1
  • 4
  • Your question is unclear please elaborate it a little more. Tell what you expect to happen? – Maheer Ali Mar 12 '20 at 10:37
  • ``` function averageCalc(year, key) { sumTotal = 0; currentYear = 'year' + year; // year2019 for (var i = 0; i < currentYear[key].length; i++) { sumTotal += currentYear[key][i]; } console.log('The total salary in ' + year + ' is ' + sumTotal); console.log(currentYear); } ``` – EugenSunic Mar 12 '20 at 10:41
  • now i get : script.js:25 Uncaught ReferenceError: salary is not defined at script.js:25 function averageCalc(year, key) { sumTotal = 0; currentYear = 'year' + year; for (var i = 0; i < currentYear[key].length; i++) { sumTotal += currentYear[key][i]; } console.log('The total salary in ' + year + ' is ' + sumTotal); console.log(currentYear); } averageCalc(2018, salary); – Yosef Mar 12 '20 at 10:58

0 Answers0