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" }
]
}];
};
-
Are datesFrom and datesTo arrays of the same length?rrowland– rrowland2015年08月06日 02:08:51 +00:00Commented Aug 6, 2015 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– Luca Luna2015年08月06日 02:10:16 +00:00Commented Aug 6, 2015 at 2:10
2 Answers 2
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" }
]
});
}
1 Comment
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.