0

Below is my javascript code:

var newData =[];
for(var j = 0; j<dates.length;j++){
    newData = [[dates[j],close[j]]];
}
document.write(newData[1]);

When I tried to print newData[2] and onwards, it shows undefined. Only newData[1] shows me the actual value. Is there anything wrong in the code above ? I am sure that dates and close array contains all the values needed

4
  • Don't use document.write! Commented Dec 30, 2015 at 15:06
  • Please show us the values of dates and close. It would also be helpful for you to create a Minimal, Complete and Verifiable Example. Commented Dec 30, 2015 at 15:06
  • Looks like you overwrite your newData array with each iteration of the loop. Commented Dec 30, 2015 at 15:09
  • Your top-level array is only one element, so newData[1] would be undefined, newData[0] would be an array containing dates[j] and close[j]. Commented Dec 30, 2015 at 15:10

2 Answers 2

4

You should push one array into outside array like this:

var newData =[];
for(var j = 0; j<dates.length;j++){
    newData.push([dates[j],close[j]]);
}

Otherwise you will overwrite you newData array in each loop

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

Comments

0

If you want to overwrite existing data of specific key, here is how you can do it:

for(var j = 0; j<dates.length;j++){
    newData[j] = [dates[j],close[j]];
}

If you want to create an array from the scratch, do as @suvroc suggested

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.