0

Think this is a simple question but just can' get my head around it;

So have these:

var students = ["Joseph", "Susan", "William", "Elizabeth"]

var scores = [ [80, 70, 70, 100], [85, 80, 90, 90], [75, 70, 80, 75], [100, 90, 95, 85] ]

var gradebook = {
Joseph: {
   testScores: scores[0]
},
Susan: {
    testScores: scores[1]
 },
William: {
   testScores: scores[2]
},
Elizabeth: {
   testScores: scores[3]
},
addScore: function(name, score) {
    gradebook[name]["testScores"].push(score);
 },
getAverage: function(name) {
    average(gradebook[name]["testScores"]);
  }
};

var average = function(array) {
  return array.reduce(function(a, b) { return a + b }) / array.length;
};

Have 2 arrays, and gradebook object, want to call gradebook.getAverage("Joseph") and return the average. but this line average(gradebook[name]["testScores"]); in getAverage function I don't think is working.

When I put the code into node terminal and then do gradebook.getAverage("Joseph"); i get undefined.

If I do average(gradebook["Joseph"]["testScores"] in the terminal I get the answer I want.

Hopefully this makes sense! thanks

2 Answers 2

2

The reason you are getting undefined from the function call is that they are not returning any value. Change it to this:

addScore: function(name, score) {
    return gradebook[name]["testScores"].push(score);
 },
getAverage: function(name) {
    return average(gradebook[name]["testScores"]);
  }
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! have just been learning Ruby and now JS, so not used to using returns
1

You need to return the value from the getAverage method:

getAverage: function(name) {
  return average(gradebook[name]["testScores"]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.