jQuery: $.unique() and text filtering

$.unique() is a jQuery utility function that returns an array without any duplicated value. This utility turns out to be very useful with simple arrays, but I think that its full potential is expressed in text filtering. Consider for example a text paragraph which contains the following text:

lorem ipsum dolor et lorem ipsum dolor sit amet

First, we need to turn this text into an array of strings:

var text = $('#test').text();
var textArray = text.split(/\s/);

Now textArray contains 9 items, and each item is a word. Since our paragraph contains the words lorem ipsum dolor repeated twice, we need to delete these duplicate entries:

var unique = $.unique(textArray);

Now our new array, called unique, contains only 6 items. We can display its contents as follows:

$('#log').text(unique.join(' '));

which outputs:

amet dolor et ipsum lorem sit

Where this feature is useful?

  1. table data sorting
  2. filtering duplicated words prior to form submission and database insertion

I think there are many other fields of possible applications but at the moment this is the simplest.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

2 thoughts on “jQuery: $.unique() and text filtering”

  1. It is not working !! I am not sure what i am doint wrong!!!

    -----------

    var text = $('#test').text();
    var textArray = text.split(/\s/);
    var unique = $.unique(textArray);
    alert (unique);
    $('#log').text(unique.join(' '));

    ---------

    div id="test" lorem ipsum dolor et lorem ipsum
    ---------

    And my result is:
    amet sit dolor ipsum lorem et dolor ipsum lorem

Leave a Reply

Note: Only a member of this blog may post a comment.