0

I want to build a 2 dimensional array dynamically, but I'm having trouble.

answers and votes (single string arrays) will always be the same length;

I need an array like this:

var data = 
 [['Answer', 'Votes'],
 [answers[0], parseInt(votes[0])],
 [answers[1], parseInt(votes[1])],
 [answers[2], parseInt(votes[2])],
 ....
 ];

This doesn't work;

var data[];
var arrayLength = answers.length;
for (var i = 0; i < arrayLength; i++) {
 data += [answers[i], votes[i]]; //**Maybe the only line that needs tweaking?
}
asked Mar 6, 2015 at 5:56
1
  • does answers array has the same length with the votes array? Commented Mar 6, 2015 at 6:04

4 Answers 4

1

Try this:

var data = [];
data[0] = ['answers','votes']
var arrayLength = answers.length;
for (var i = 0; i < arrayLength; i++) {
 data[i+1]= [answers[i], parseInt(votes[i])]; 
}
//check
console.table(data)
answered Mar 6, 2015 at 6:03
Sign up to request clarification or add additional context in comments.

Comments

1
var data = [];
var arrayLength = answers.length;
data[0] = ['Answer', 'Votes'];
for (var i = 1; i < arrayLength; i++) {
 data.push([answers[i], votes[i]]); /*It's not += but .push()*/
}
answered Mar 6, 2015 at 6:03

2 Comments

Ah yeah. I've missed it. Thanks for the notice.
he copied off my bad declaration ;) .. Thanks @Xlander
0

Try this:

var data = [];
var arrayLength = answers.length;
for (var i = 0; i < arrayLength; i++) {
 data.push([answers[i], votes[i]]);
}
answered Mar 6, 2015 at 6:07

Comments

0

Since you wrote answers [i] and votes[i] so, it seems your answers and votes are in two different array. so why the loop is needed.

Suppose answers and votes are:

var answers = ["A", "B", "C", "D", "E", "F"];
var votes = ["1", "2", "3", "4", "5", "6"];

building new array

var data = ["Answers", "Votes"];
data.Answers=answers;
data.Votes=votes;
console.log(data);
answered Mar 6, 2015 at 8:53

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.