Reputation: 159
I have the following snippet of code which intends to update the value of the array "end" each time the if statement evaluates as true(in this case it equals to three). However, the array just gets superseded by the last update and all previous values are deleted. How can it be appended with the new set of values?
d.forEach(function (d) {
if (d.state_type=="end") {
end=d.user_ids;
}
});
Upvotes: 0
Views: 68
Reputation: 63524
Loop over the d.user_ids
array and push them into end
one by one:
function whatever() {
var end = [];
d.forEach(function (d) {
if (d.state_type == "end") {
for (var i = 0, l = d.user_ids.length; i < l; i++) {
end.push(d.user_ids[i])
}
}
});
return end;
}
Alternatively, you could do what you were doing originally but flatten the array afterwards:
function whatever() {
var end = [];
d.forEach(function (d) {
if (d.state_type == "end") {
end.push(d.user_ids)
}
});
var merged = [];
return merged.concat.apply(merged, end);
}
Upvotes: 1
Reputation: 25882
Your array end
is undefined here.
You can add values in array using Array.push(value)
.
var end = end || []; //Here I am just making sure if end array doesn't exist create one.
d.forEach(function (d) {
if (d.state_type=="end") {
end.push(d.user_ids);
}
});
Upvotes: 0
Reputation: 67
You need to use:
end.push(d.user_ids);
You also need to make sure that end
is an array so your loop could be:
d.forEach(function (d) {
if (d.state_type=="end") {
if (typeof end == "undefined") {
end = [];
}
end.push(d.user_ids);
}
});
Upvotes: 0