比较两个数组并创建第三个数组

时间:2020-12-12 12:19:56

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

2 个解决方案

#1


5  

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.

目前,您正在将7天内的索引i中的值与json[0]的索引i中的对象的值属性进行比较,但这并不正确,因为顺序不匹配。09的值在json[0]的索引2处,而09在7天的索引5处。

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

您将需要在七天内进行迭代,对于每个迭代,都要遍历json[0]以找到匹配的对象,如下所示:

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.

看看这个工作演示。

#2


0  

considering your second array in proper json format ....

考虑你的第二个数组的json格式....

you can do it like this

你可以这样做。

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 :)
}
}
}

#1


5  

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.

目前,您正在将7天内的索引i中的值与json[0]的索引i中的对象的值属性进行比较,但这并不正确,因为顺序不匹配。09的值在json[0]的索引2处,而09在7天的索引5处。

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

您将需要在七天内进行迭代,对于每个迭代,都要遍历json[0]以找到匹配的对象,如下所示:

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.

看看这个工作演示。

#2


0  

considering your second array in proper json format ....

考虑你的第二个数组的json格式....

you can do it like this

你可以这样做。

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 :)
}
}
}