I am having difficulty pushing objects to an array of arrays via indices. Find below my current (awfully duplicative code) which reads through a CSV file's lines (Format: Date, reasonCode), and then creates FROM and TO (date) pairs depending on the reasonCode. This array is then used for Highcharts (Gantt chart). Please note the fromto1
and fromto2
arrays.
csv = csv.split(/\n/g);
var fromto1 = []; //array of FROM and TO pairs of code 1
fromto2 = []; //array of FROM and TO pairs of code 2
count = [];
lastFrom = [];
for (var i=1;i<3;i++) { //set all count and lastFrom variables to 0 //bs
count[i] = 0;
lastFrom[i] = 0;
}
jQuery.each(csv, function(i, line) {
line = line.split(','); //splits line, returns array of splitted values
date = parseInt(line[0], 10)*1000; //read date from line into string
reasonC = parseInt(line[2], 10); //read reasonC from line into string
if (reasonC == "1") {
count[1]++;
if (count[1] % 2 !=0){ //if it is an uneven value (FROM values)
lastFrom[1] = date; //temporary save the date in lastFrom[]
}
else { //if it is an even value (TO value), push the pair
fromto2.push({
from: lastFrom[1],
to: date
});
}
}
if (reasonC == "2") {
count[2]++;
if (count[2] % 2 !=0){
lastFrom[2] = date;
}
else {
fromto3.push({
from: lastFrom[2],
to: date
});
}
}
Why can't I replace the above code with this (Please note the fromto
array of arrays):
csv = csv.split(/\n/g);
var fromto = [];
count = [];
lastFrom = [];
for (var i=1;i<3;i++) { //set all count and lastFrom variables to 0
count[i] = 0;
lastFrom[i] = 0;
fromto.push(new Array());
console.log(i+': New Array Pushed');
}
jQuery.each(csv, function(i, line) {
line = line.split(','); //splits line, returns array of splitted values
date = parseInt(line[0], 10)*1000; //read date from line into string
reasonC = parseInt(line[2], 10); //read reasonC from line into string
for (var c=1;c<3;c++) {
if (reasonC == c.toString()) {
count[c]++;
if (count[c] % 2 !=0){ //if it is an uneven value (FROM values)
lastFrom[c] = date; //temporary save the date in lastFrom[]
}
else { //if it is an even value (TO value), push the pair
fromto[c].push({
from: lastFrom[c],
to: date
});
}
}
}
}
I believe the problem is with fromto[c].push({
as it stays blank arrays.
I'm still a Jsnoob and couldn't find any answers on other threads, your help would be highly appreciated
var
. If you wanted to declare multiple vars, don't use;
, use,
. Also, don't usenew Array
.fromto.push(new Array())
=>fromto.push([])
– Mike 'Pomax' Kamermans Sep 2 at 17:19