Cannot read property Score

This is a classic array overflow issue. You loop over an array, getting the value after the current value to compare it to. Only when you get to the last value, there is no entry after that, so Source[nexIndx] is undefined.

The solution is either to stop one earlier by not executing this code for the last element, or to start one later (i = 0 becomes i = 1) and look backwards instead of forwards. I show the latter below:

var Source = [{
    "Name": "Man U",
    "Games": 34,
    "Score": 12
  },
  {
    "Name": "Man U",
    "Games": 4,
    "Score": 132
  },
  {
    "Name": "Man U",
    "Games": 3,
    "Score": 5
  },
  {
    "Name": "Man U",
    "Games": 24,
    "Score": 120
  },
  {
    "Name": "Man U",
    "Games": 1,
    "Score": 56
  },
  {
    "Name": "Man U",
    "Games": 7,
    "Score": 7
  },
  {
    "Name": "Man U",
    "Games": 14,
    "Score": 5
  }
];

var newData = [];
var i;
for (i = 1; i < Source.length; i++) {
  if (Source[i - 1].Score === 5) {
    if (Source[i].Score == 120) {
      newData.push(Source[i - 1], Source[i]);
    }
  }
}
console.log(newData);

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top