I am trying to only print a unique value of ‘sum’ by doing a compare at the end of the loop, but I’m seeing that every time it does a compare it has already moved on to the next element and therefore when its comparing the two values they’re always the same. Is there another way to do this?
$(document).ready(function(){
$.getJSON('XML.php', function(data) {
JSON.stringify(data);
var prevCardCode = '';
$.each( data, function(index, element){
var prevCardCode = element['CardCode'];
if (!(element['CardCode'] == prevCardCode)) {
var sum = element['payment_sum'] + '<br/>';
$('#showdata').append(sum);
}
alert(element['CardCode'] + 'compare' + prevCardCode);
});
});
});
The
varkeyword doesn’t belong within the each in this case, and you need to move it to after the comparison.If the
varis left in place beforeprevCardCode, it will never set the one defined outside of the$.eachand will not carry over to the next iteration of$.each.