0

Having some trouble with this script. It iterates through a two dimensional array and adds each corresponding index together. So basically arr[0][1] + arr[0][2] + arr[0][3] ... arr[1][1] + arr[1][2] + arr[1][3] ...etc.

This first one works fine. So my logic is ok. My problem here is that I can't create the indices dynamically. I don't think a push will work since I'm summing values here.

var cat_stats_week_radar = [[0,0,0,0,0,0,0,0,0,0,0,0,0,0]];


    for (var i = 0; i < cat_stats_week.length; i++) {
        for (var j = 0; j < cat_stats_week[0].length; j++) {
            cat_stats_week_radar[0][j] += +(cat_stats_week[i][j]);
        }

}

This one doesn't work, I don't get an error, just a bunch of NaN values.

var cat_stats_week_radar = [[]];


    for (var i = 0; i < cat_stats_week.length; i++) {
        for (var j = 0; j < cat_stats_week[0].length; j++) {
            cat_stats_week_radar[0][j] += +(cat_stats_week[i][j]);
        }

}

Here are the arrays I'm working with.

Array to add:

var cat_stats_week = [
[0,0,0,0,0,0,0,1,0,0,0,0,0,0],
[0,0,0,0,0,0,1,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,1,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,1,0],
[0,0,0,0,0,0,0,0,0,0,0,0,1,0],
[0,0,1,0,0,0,0,0,0,0,0,0,0,0]
];

Resulting array:

var cat_stats_week_radar = [[0, 0, 1, 0, 0, 0, 2, 1, 0, 0, 0, 0, 2, 0]];

1 Answer 1

2

You need to initialize it with the right number of zeroes:

var cat_stats_week_radar = [[]];

for (var i = 0; i < cat_stats_week[0].length; i++) {
    cat_stats_week_radar[0].push(0);
}

And with Underscore.js:

_.map(_.zip.apply(null, cat_stats_week), function(a) {
    return _.reduce(a, function(a, b) {
        return a + b
    })
});
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.