Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two arrays and create third one

Tags:

arrays

jquery

I have two arrays that I tried to compare and create third one

my first array:

sevenDays = ["04","05","06","07","08","09","10"];

my second array:

   json[0] =  [Object{day="04",value="5"}, Object { day="05",value="8"}, Object { day="09",value="9"}]

what I am trying to get is:

 [[04,5],[05,8],[06,0],[07,0],[08,0],[09,9],[10,0]]

I tried like this

var desiredArray= [];                           
$.each(sevenDays, function (i, v) {
   val= 0;
     if (json[0][i].value) val = json[0][i].value;
     desiredArray[i] = [v, val]
}); 


 [[04,5],[05,8],[06,9],[07,0],[08,0],[09,0],[10,0]] //output
like image 971
InTry Avatar asked Mar 05 '13 12:03

InTry


1 Answers

You're currently comparing the value from index i in sevenDays to the value property of the object at index i of json[0], but that's not correct because the order doesn't match up. The value for 09 is at index 2 in json[0] but 09 is at index 5 in sevenDays.

You'll need to iterate over sevenDays, and for each iteration iterate over json[0] to find the matching object, like so:

var desiredArray = [];

$.each(sevenDays, function (i, day) {
    val = 0;
    $.each(json[0], function(j, value) {
        if(day == value.day)
            val = value.value;
    });
    desiredArray[i] = [day, val];
});

Take a look at this working demo.

like image 77
Anthony Grist Avatar answered Sep 30 '22 07:09

Anthony Grist