FECoder
FECoder

Reputation: 27

jquery unique array values

I have the following code which gets values of table cells into arrays based on a data type applied to the table row:

 $("#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() );
});

Is it at all possible to modify this code so that only unique values are stored? I'd much prefer to tweak the above rather than consider alternative solutions or additional libraries as this might require reworking of already functioning code.

I've had a good scoot round but I'm not able to find anything that uses the above type of solution.

Thanks for any suggestions you can offer me.

Upvotes: 0

Views: 199

Answers (1)

Volune
Volune

Reputation: 4339

First, variables and line returns will make your code a lot more readable:

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

Now you can use indexOf to check if the value is not yet inserted:

$("#pricehistory tr").each(function (index, el) {
    var day = $(el).data('day');
    var value = $(el).find('td:last').text();
    if ( ! (day in dataAttributes) )
        dataAttributes[day] = [];
    if ( dataAttributes[day].indexOf(value) < 0 ) //< 0 means not found
        dataAttributes[day].push( value );
});

(And you can use a polyfill if you want IE8 compatibility)

Upvotes: 1

Related Questions