Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

I am trying to loop through two arrays of dates, dateFrom and dateTo to use in a gantt chart plugin. The gantt chart requires ganttData. I want to loop through these two arrays simultaneously and create ganttData as an array of arrays. Right now, it is looping simultaneously through both arrays but ganttData is only the last index of both arrays, which makes sense because I am just reassigning the values each time through the loop.

I tried using += instead of = but I get an error:

Uncaught TypeError: Cannot read property 'length' of undefined

Below is the code that I have so far:

These arrays are correct Ive checked.

I am unfamiliar with JS so any and all help is greatly appreciated. Thank you!

var datesFrom = <%= dates_from %>
var datesTo = <%= dates_to %>
//var ganttData = [] if I were to use ganttData += [ below 

output = []
i;

for (i = 0; i < (datesFrom.length - 1); i += 1) {
    ganttData = [{
        id: 1, name: "Feature 1", series: [
            { name: "Planned", start: new Date(datesFrom[i]), end: new Date(datesTo[i]) },
            { name: "Actual", start: new Date(datesFrom[i]), end: new Date(datesTo[i]), color: "#f0f0f0" }
        ]
    }];
};  
share|improve this question
    
Are datesFrom and datesTo arrays of the same length? – rrowland Aug 6 at 2:08
    
Yes they are for now! In the future they may vary but I think I can handle that in the rails code. – Luca Luna Aug 6 at 2:10
up vote 1 down vote accepted

Assuming datesTo and datesFrom are the same length, you'll want to create an array (ganttData) and push a new object to it for each pair of dates, like so:

var ganttData = [];

for(var i = 0; i < datesFrom.length; i++) {
  ganttData.push({
    id: i,
    name: "Feature " + i,
    series: [
      { name: "Planned", start: new Date(datesFrom[i]), end: new Date(datesTo[i]) },
      { name: "Actual", start: new Date(datesFrom[i]), end: new Date(datesTo[i]), color: "#f0f0f0" }
    ]
  });
}
share|improve this answer
    
Thank you so much! worked perfectly. my day just got much better! – Luca Luna Aug 6 at 2:14

In general, to build up an array, you'd use this pattern:

var ganttData = [];
for (...) {
  ganttData.push({...});
}

In JavaScript, as opposed to say Ruby, array1 + array2 is not defined: it will convert both arguments to strings and concatenate those instead. For array concatenation, you need to use array1.concat(array2), or if you want a destructive method (i.e. to change array1), array1.push.apply(array1, array2); but for appending one element, push is a better choice.

share|improve this answer
    
Thank you for the pattern! I will keep this in mind! – Luca Luna Aug 6 at 2:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.