0

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;
  }      
});
Andy
  • 61,948
  • 13
  • 68
  • 95
VerletIntegrator
  • 159
  • 2
  • 10
  • 1
    [`end.push(d.user_ids)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) – Andy Jul 18 '14 at 16:19
  • I tried this before posting the question, error message:Uncaught TypeError: Cannot read property 'push' of undefined – VerletIntegrator Jul 18 '14 at 16:21
  • Then `end` either doesn't exist or it isn't an array. – Andy Jul 18 '14 at 16:22
  • `end` is infact `undefined` – techfoobar Jul 18 '14 at 16:23
  • OK, so I had forgotten to declare "end" inside the function. However, now although the values are getting stored, its stored as an object of 3 arrays. I want one single array containing the appended values. – VerletIntegrator Jul 18 '14 at 16:27
  • `var end = d.filter(v => v.state_type === 'end').map(v => v.user_ids).reduce((a, b) => a.concat(b), [])` would be the es6 equivalent expression to use. – Sean Kinsey Jul 18 '14 at 16:49

3 Answers3

1

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

DEMO

Community
  • 1
  • 1
Andy
  • 61,948
  • 13
  • 68
  • 95
0

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);
    }      
});
Nathan Boiron
  • 67
  • 1
  • 3
0

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);
  }      
});
Mritunjay
  • 25,338
  • 7
  • 55
  • 68