jQuery Unique, difference in Chrome and Firefox?

Asked

Viewed 248 times

4

I’m having an unexpected behavior with the uniquejQuery.

The following command:

 var x = [1,2,1,2];
 var y = $.unique(x);
 document.write(y);

Chrome results in 1,2 (which is correct), but in Firefox appears 1,2,1,2.

Is this a bug, or was it meant to be that way?

Here is an example from jsfiddle, open first in Chrome (works correctly) and then in Firefox (doesn’t work).

OBS: jQuery 2.1.0; Firefox 24.5.0; Google Chrome 34.0.1847.131 m.

  • 3

    I found on jQuery bugs page the following: $.unique() is only designed to work on DOM nodes, not on arrays of strings. http://bugs.jquery.com/ticket/7036

  • @Sergio, the bug is closed as invalid > "closed bug: invalid"

  • @guisantogui The bug is invalid precisely because the function is being used differently than it was designed.

  • Hint: To get unique elements from an Array, convert it to an object. Every Javascript object is practically a dictionary, so you can guarantee the uniqueness ;) Example with all values like true: var z = {"1": true, "2": true};

1 answer

5


The .unique()jQuery was not designed for numbers or strings. jQuery documentation reads:

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.

in our language it would be:

Sorts an array of DOM elements by removing duplicates. Note that this only works on DOM elements and not numbers or strings.

Here is javascript code to do what you need: http://jsfiddle.net/4SBVQ/

var arrayUnique = function(a) {
    return a.reduce(function(p, c) {
        if (p.indexOf(c) < 0) p.push(c);
        return p;
    }, []);
};

Source: https://stackoverflow.com/a/4833835/2256325

Browser other questions tagged

You are not signed in. Login or sign up in order to post.