Alko
Alko

Reputation: 1439

jQuery, javascript, find all unique links on page

I'm trying do do something like this:

   var items = $("main a").unique();
   var links = [];
   items.each(function (index, value)
   {
        links.push({
            href: this.href, 
            text:  this.text
        });
   });

the idea is to find all links on page and remove duplicates, producing an object with href/text pairs. But the above does not work, I'm getting "TypeError: $(...).unique is not a function"

Upvotes: 0

Views: 135

Answers (2)

cowbert
cowbert

Reputation: 3442

You are calling $.unique() incorrectly. It is not a method of the jQuery object, it is an actual function. You really want:

$.uniqueSort($("main a"))

Also, learn to use .map() instead of pushing arrays:

var links = $.uniqueSort($("main a")).map(function(idx, e) {
    return {href: e.href, text: e.text}
})

(Note: this .map() is the jQuery version, where the first argument to the callback is the array/object's index instead of the array element, because $.uniqueSort() applied to a jQuery object returns a jQuery object not a native JavaScript array).

Upvotes: 2

Sebastien D
Sebastien D

Reputation: 4482

The correct syntax for unique in jQuery is :

$.uniqueSort()    

$.unique() is deprecated as of jQuery 3.0

Upvotes: 0

Related Questions