0

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

3 Answers 3

1

The var keyword doesn't belong within the each in this case, and you need to move it to after the comparison.

var prevCardCode = ''; $.each(data, function(index, element) { if (!(element['CardCode'] == prevCardCode)) { var sum = element['payment_sum'] + '<br/>'; $('#showdata').append(sum); } alert(element['CardCode'] + 'compare' + prevCardCode); prevCardCode = element['CardCode']; });​ 

If the var is left in place before prevCardCode, it will never set the one defined outside of the $.each and will not carry over to the next iteration of $.each.

Sign up to request clarification or add additional context in comments.

1 Comment

I thought I did explain it pretty well. Basically, if you include the var keyword, you are creating a new variable within the scope of the $.each rather than using the existing variable in the parent scope. Additionally, you need to compare the value before you override it for the next iteration.
1

You need to move the prevCharCode assignment to the end of the loop and remove the var in front of it:

var prevCardCode = ''; $.each( data, function(index, element) { if (!(element['CardCode'] == prevCardCode)) { // your code... } prevCardCode = element['CardCode']; }); 

Comments

0

prevCardCode is not the precedent element but the current... Then you compare current with current...

If you want to compare precedent element with current, you should use a while or a do while.

var i = 1; var precedentEl = array[0]; while (i < array.length) { // Do some stuff like compare current and precedent precedentEl = array[i]; i++; } 

Secondly, you call XML.php which return json... It's sound strange...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.