0

I have a table and each table row is dynamically assigned a data-day attribute by unique date. The output of which is similar to the following:

<table id="pricehistory">
<tr data-day="1">
   <td>Thu 22/08/13 00:00</td>
   <td>value 1</td>
</tr>
<tr data-day="1">
   <td>Thu 22/08/13 00:00</td>
   <td>value 2</td>
</tr>
<tr data-day="1">
   <td>Thu 22/08/13 00:00</td>
   <td>value 3</td>
</tr>
<tr data-day="2">
   <td>Mon 14/01/15 00:00</td>
   <td>value 2</td>
</tr>
<tr data-day="3">
   <td>Tues 15/01/15 00:00</td>
   <td>value 3</td>
</tr>
</table>

Based on a previous answer, I'm using the following to get an array for each unique datatype with the associated values:

var allAvailableOptions = ["value 1","value 2","value 3"];

var dataAttributes = {};

$("#pricehistory tr").each(function (index, el) {
   if ( ! ($(el).data('day') in dataAttributes) ) dataAttributes[$(el).data('day')] = [];
   dataAttributes[$(el).data('day')].push( $(el).find('td:last').text() );
});

Building on what I've got so far, what I'd like to achieve is the following:

  1. For each of my arrays, only push items in when they don't already exist (resulting in only unique values within each array)
  2. Compare each of my "values" arrays to my "allAvailableOptions" array and return true of false if they match.

Based on responses so far I've made edits and used toString() which seems to work:

$.each(dataAttributes, function (i, v) {
   var thisArray = this.toString();
   if(thisArray == allAvailableOptions){
      alert("match")
   }
   else
   {
      alert("no match")
   }
});

Although this may not be a good way of doing it (I'm sure someone will point out why) it seems to be functioning exactly as intended and so I'm happy with this approach:

http://jsfiddle.net/zqbn983d/8/

All I need to determine now is how to ensure my arrays don't have any duplicates and only push if the value doesn't already exist.

Any help that can be offered is greatly appreciated

Cheers

FECoder
  • 27
  • 1
  • 6

1 Answers1

1

No, equals on arrays does not work that way, you're trying to compare objects, which in this case are different array objects.

You should be inspecting the contents. See this answer for a sensible implementation.

Also, in this case, your use of

var $this = $(this);

is utterly redundant as it's never referenced.

Community
  • 1
  • 1
Jeff Watkins
  • 6,343
  • 16
  • 19
  • 1
    Ah yes, apologies for that. I've been copying and pasting from other examples of code I've got. – FECoder Aug 31 '14 at 15:10
  • I've now edited my code to remove the redundant code mentioned, and also updated with a toString() approach that seems to achieve my requirements. Thanks – FECoder Aug 31 '14 at 15:41