0

I have an array which looks like this

var x = [
    {
        "name" : "Paris",
        "count" : [1,30, 20]
    },{
        "name" : "London",
        "count" : [5,30, 10]
    }
]

I am trying to resolve into something this by adding the numbers of the property "count"

var y = [
    {
        "name" : "Paris",
        "count" : 51
    },{
        "name" : "London",
        "count" : 45
    }
]

Here is my code

var y = []
function doTotal(x, i){
    var out = 0;
    for(var j = 0; j < x[i].count.length; j++){
        out += x[i].count[j];
    }
}
for(var i = 0; i < x.length; i++){
    y[i] = {
        name : x[i].name,
        total : doTotal(x, i)
    }
}

console.log(y)

..total is undefined. What am I doing wrong?

2
  • 3
    doTotal() doesn't currently return a value. Commented Jun 10, 2015 at 22:54
  • yes..thats all it was...i pulled my hair out for an hour with this Commented Jun 10, 2015 at 23:00

1 Answer 1

2

You need to return variable out inside dototal function

var x = [
    {
        "name" : "Paris",
        "count" : [1,30, 20]
    },{
        "name" : "London",
        "count" : [5,30, 10]
    }
]
var y = [
    {
        "name" : "Paris",
        "count" : 51
    },{
        "name" : "London",
        "count" : 45
    }
]
function doTotal(x, i){
    var out = 0;
    for(var j = 0; j < x[i].count.length; j++){
        out += x[i].count[j];
    }
    return out;
}
for(var i = 0; i < x.length; i++){
    y[i] = {
        name : x[i].name,
        total : doTotal(x, i)
    }
}
alert(JSON.stringify(y));

Sign up to request clarification or add additional context in comments.

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.