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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With