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?
}
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)
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()*/
}

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]]);
}

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);

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.