Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Unique() function not working properly

I'm working on an interface that allows the user to select multiple "cards". Each card has a "data-name" attribute and may also have a corresponding menu item. If they select the card in the main view, it also highlights the menu item. When something is clicked, I add the "selected" class to it. I then get all the 'selected' items and count the unique data-name attributes to get the number of actual items selected.

This works very well when selecting up to 5 items. For some reason, on the 6th item the unique() function seems to stop working correctly. I was unable to duplicate this issue with jsfiddle, but the code was a bit less complex, as locally I'm also dealing with "types", but I think that's irrelevant to the problem.

So here are some screenshots of the relevant arrays after I have selected the 5th item.

Here you see ALL selected items. There are 10, as expected. This breakpoint is just before the unique() call. Here you see ALL selected items.  There are 10, as expected.

Here you see unique selected items. There are 5, as expected. Here you see unique selected items.  There are 5, as expected.

And then I select the 6th one... 12, as expected... And then I select the 6th one...

Aaand now we have a mysterious duplicate! Why??? enter image description here

This happens consistently; every single time. And note that it doesn't matter which item I select last. I've added as many as 10 dummy items and it's always the 6th one that it gets confused on.

like image 741
THE JOATMON Avatar asked Nov 13 '13 19:11

THE JOATMON


1 Answers

Taken from jQuery.unique():

Description: Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.

If you want to get a unique array of string or numbers, you will need to use your own function. Here's one taken from a previously answered question similar to yours:

function unique(array) {
    return $.grep(array, function(el, index) {
        return index == $.inArray(el, array);
    });
}
like image 62
Nahydrin Avatar answered Nov 05 '22 05:11

Nahydrin