0

I have two arrays that i would like to compare the values at a certain index.

$("#sortable").sortable().bind('sortupdate', function() {
    var id = $( "#sortable" ).sortable( "toArray" );
    console.log(id); 
    var compare = id.sort(function(a,b){return a - b});
    console.log(compare);
    var completion = 0;
    for (i = 0; i < 10 ; i++) {
       completion += (id[i] == compare[i]);
    }
    console.log(completion)
  });
});

When I check the console I am told that 10 are equal no matter. This is what the console returns. I have the id array first and the compare array second and the completion variable third. I expect the completion variable to return 0 for this case.

["19", "26", "3", "27", "25", "8", "42", "11", "24", "37"] (index):66

["3", "8", "11", "19", "24", "25", "26", "27", "37", "42"] (index):68

10

Anyone have any ideas?

  • Im guessing we're missing some other code based on those closing parenthesis - can you replicate this in a fiddle? – tymeJV Aug 06 '14 at 19:43

2 Answers2

3

You're running nested loops. For each iteration of the i loop, you do all 10 iterations of the j loop. So you're testing EVERY value in the id array against EVERY value of the compare array - 100 comparisons.

If you want to compare position against position, you just need ONE loop:

for (i = 0; i < 10 ; i++) {
   count += (id[i] == compare[i]);
}
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • The console still returned 10, the two arrays are coming from a sortable list thru sortupdate which grabs the ids from li. The first is the unordered array and the second is the sorted array which I want to compare with to determine if the list items are in the correct place. Does this change the way I would compare the two? – user3892916 Aug 06 '14 at 19:55
1

You only need one loop to compare two arrays at the same index:

for (var ii = 0; ii < ii.length; ii++) {
  if (id[ii] == compare[ii]) {
    completion++;
  }
}

This assumes that they arrays are the same length. If they are different lengths, you can only compare up to the length of the shortest array:

var shortestLength = (id.length < compare.length) ? id.length : compare.length;
for (var ii = 0; ii < shortestLength; ii++) {
  if (id[ii] == compare[ii]) {
    completion++;
  }
}
Peter Gluck
  • 8,168
  • 1
  • 38
  • 37