0

I have a javascript matrix array with the following structure (the first index is x, the second index is y, so every x item has 4 y items):

0 
 0 { x: 0, y: 0, z: 0}
 1 { x: 0, y: 1, z: 5}
 2 { x: 0, y: 2, z: 0}
 3 { x: 0, y: 3, z: 1}
1
 0 { x: 1, y: 0, z: 4}
 1 { x: 1, y: 1, z: 5}
 2 { x: 1, y: 2, z: 1}
 3 { x: 1, y: 3, z: 8}

What I need to do is get an array that stores the z values per y value. So for all the values of x I need the total values of z arranged by y. The structure I am looking for (assuming 4 y values)

0 4
1 10
2 1
3 9

I tried this:

count = [];
 $.each(matrix, function(i, j) {
 $.each(j, function(k, v) {
 count[k] += v["z"];
 }) 
 });

But this returns just an array with NaN values. Does anyone have better suggestions?

asked Sep 15, 2014 at 11:05
1
  • Where are your array var definitions? Must they be arrays or can they be objects? Commented Sep 15, 2014 at 11:11

2 Answers 2

1

You need to initialize count array

var count=[ 0, 0, 0, 0];
$.each(matrix, function(i, j) {
 $.each(j, function(k, v) {
 count[k] += parseInt(v["z"],10);
 }) 
});
answered Sep 15, 2014 at 11:11
Sign up to request clarification or add additional context in comments.

2 Comments

Great, now could I initialize the count automatically with the length of the y array? So that I don't have to enter another 0 if the y array gains an item?
Never mind, I came across this: stackoverflow.com/questions/1295584/…
0

Your count array is not initialized, and you are trying to do math with undefined, so your result is NaN. Initialize count array with zeros.

answered Sep 15, 2014 at 11:18

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.