0

I am looping through an array called race and within it is an array called time. I need to compare the contents of the array time with the contents of the array speed. If both contents exactly match, I need to push race[i] into the empty array called filtered. For some reason, when I run this filter, all arrays within race are pushed into filtered. Any idea why it would be doing this? Here's the code:

angular
  .module('raceApp')
  .filter('certFilter', function() {
  return function(race, speed) {
    var filtered = [];
    for (var i = 0; i < race.length; i++) {
      for (var k = 0; k < race[i].data.time.length; k++) {
        for (var j = 0; j < speed.length; j++) {
          if (race[i].data.time[k] === speed[j] && filtered.indexOf(race[i]) == -1) {
            filtered.push(race[i]);
          } else {
            filtered.splice(i, 1);
          }
        }
      }
    }
    console.log('filtered', filtered);
    return filtered;
  }
});


console.log('filtered', filtered);
return filtered;
}
});
bhood
  • 355
  • 2
  • 8
  • 18
  • You're not comparing the whole contents, you're just comparing individual elements. – Barmar Aug 27 '17 at 14:47
  • @Barmar what's the best way to compare the whole contents without looping? – bhood Aug 27 '17 at 14:53
  • You have to loop. But not nested loops like you have. You should be looping once, comparing corresponding elements in both arrays. Isn't it explained well in the linked question? – Barmar Aug 27 '17 at 14:54

0 Answers0