1

I'am trying to compare 2 date arrays(all_date, click_date) and set value 0 in array clicks if date not exist in array click_date

all_date=["2015-10-17", "2015-10-18","2015-10-19", "2015-10-20","2015-10-21","2015-10-22"]

click_date=["2015-10-17", "2015-10-19", "2015-10-20"]

clicks=[5,3,1]

Final result:

clicks=[5,0,3,1,0,0]

i used this code:

if(key==0){
  $.each(all_date, function( j, v ) {

      if(dateInitial==v){

        clicks[0].push(parseInt(val["nbrclick"]));
        return false;

      }else{

        clicks[0].push(0);

      }
  });   
  }else{

    for (i=0; i < key; i++){

      $.each(all_date, function( j, v ) {

        if(dateInitial==v){

          clicks[key].push(parseInt(val["nbrclick"]));
          return false;

        }else{

          clicks[key].push(0);

        }
      });
    }
}

but i get clicks array like this [5,0,0,3,0,0,0,1,0...]

what is missing in my code?

2
  • what does dateInitial contain? Commented Oct 30, 2015 at 11:15
  • dateInitial contain first date from array click_date Commented Oct 30, 2015 at 11:21

1 Answer 1

4

You can simply generate a new array using Array.prototype.map which generates a new array by applying a custom function to every item in an array.

For every item do the following:

  • if such date exists in click_date, then get this index and find clicks[index]
  • if such date does not exist - simply return 0

var all_date=["2015-10-17", "2015-10-18","2015-10-19", "2015-10-20","2015-10-21","2015-10-22"];
var click_date=["2015-10-17", "2015-10-19", "2015-10-20"];
var clicks=[5,3,1];

var result = all_date.map(function(x) {
  var indexInClickDate = click_date.indexOf(x);
  return (indexInClickDate > -1) ? clicks[indexInClickDate] : 0;
});

document.body.innerHTML = JSON.stringify(result);

Just to make it easier to understand, an algorithm above does almost the same as:

var all_date=["2015-10-17", "2015-10-18","2015-10-19", "2015-10-20","2015-10-21","2015-10-22"];
var click_date=["2015-10-17", "2015-10-19", "2015-10-20"];
var clicks=[5,3,1];

var result = [];

for (var i = 0; i < all_date.length; i++)
{
  var indexInClickDate = click_date.indexOf(all_date[i]);
  if (indexInClickDate > -1)
    result.push(clicks[indexInClickDate]);
  else
    result.push(0);
}

document.body.innerHTML = JSON.stringify(result);

However, map() function is more convenient to work with.

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

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.