Vertisan Vertisan - 2 months ago 7
jQuery Question

Comparison of 2 tables do not always work

I need to compare records of two arrays and add style if are equal.

I do this:

var json = ["VIP Section","Master Section","Press Section","God Section"];
var sections = ["VIP Section","Master Section"];

if ( sections.length > 0 ) {
for (i = 0; i < json.length; i++) {
if ( json[i] == sections[i] ) {
$('#test-ul').append('<li style="color: red;">' + sections[i] + '</li>');
} else {
$('#test-ul').append('<li>' + json[i] + '</li>');
}
}
} else {
$('#test-ul').append('<li>No sections!</li>');
}


However, this does not always work ...

Once I have colored equals elements but next I time I have all elements without color.

enter image description here

...

enter image description here

Where is bad? Or maybe is another solution for this?

Answer

The way you have it set up, it will compare each element at the same position in the array. For instance it only compares the first item in json to the first item in sections and so on. If your goal is to find out if any of the elements of json are also in sections and in any order, then use indexOf() on each item in json to determine if the array item exists also in sections. This will work no matter what order they are in.

When you use indexOf() on an array it will return the position in the array where the item is found. If it does not exist it will return -1.

Note in the snippet below, I moved your second array item in json to the end of the array to prove this point.

var json = ["VIP Section","Press Section","God Section","Master Section"];
var sections = ["VIP Section","Master Section"];

if ( sections.length > 0 ) {
  for (i = 0; i < json.length; i++) {
      if ( sections.indexOf(json[i]) > -1 ) {
        $('#test-ul').append('<li style="color: red;">' + json[i] + '</li>');
      } else {
        $('#test-ul').append('<li>' + json[i] + '</li>');
      }
  }
} else {
  $('#test-ul').append('<li>No sections!</li>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="test-ul"></ul>

Further reading:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf