Compare two arrays and create a third

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

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"}]

I am trying to get:

 [[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
+5
source share
2 answers

You are currently comparing the value from index iin sevenDaysto the property of the valueobject in index ifrom json[0], but this is incorrect because the order does not match. The value 09has index 2 in json[0], but 09has index 5 in sevenDays.

You will need to iterate through sevenDays, and for each iteration through iteration to json[0]find the corresponding object, for example:

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 .

+5
source

given your second array in native json format ....

you can do it like that

var data[] =["",""]
for(value in sevenDays)
{
for(Object in json[0])
{
if(Object.hasOwnProperty(data[value])
{
     // do ur stuff here :)
}
else
{
     //do the other stuff here :)
}
}
}
0
source

All Articles