1

I have a problem merging 2 arrays in an for loop see code:

function count_days(tijden,datums ){

        var length = tijden.length;
        element = null;
        var similarities =0;
        var backup = [];
        var dateArray =[];

        for (var i = 0; i <length; i++) {
                element = tijden[i];
                tijden[i] = element;


            dateArray = getDates(new Date(tijden[i]['begin']), new Date(tijden[i]['eind']));


         }

The problem is that when the code is running i get one array for each loop. I need to get one array with the data from all loops. I tryde concat but didnt get this to work

0

1 Answer 1

1

It should be...

dateArray.push(
  getDates(new Date(tijden[i]['begin']), new Date(tijden[i]['eind']))
);

... or, if getDates method returns an array and you want dateArray to be flattened:

Array.prototype.push.apply(dateArray,
  getDates(new Date(tijden[i]['begin']), 
           new Date(tijden[i]['eind']))
);

As it stands now, you just rewrite dateArray at each step of for loop.


A sidenote: this...

element = tijden[i];
tijden[i] = element;

... makes exactly zero sense: at least one of these lines (most probably the latter) is redundant. Remove this - and code becomes easier to read:

var element, currDates;
for (var i = 0, i < length; i++) {
  element = tijden[i];
  currDates = getDates(new Date(element.begin), new Date(element.eind));
  Array.prototype.push.apply(dateArray, currDates);
}
0

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.