Click here to Skip to main content
12,954,203 members (73,711 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


Posted 6 Sep 2013

Filtering Array and Getting the Index of an Element in jQuery

, 6 Sep 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
Filtering array and getting the index of an element in jQuery

Consider an example of getting unique elements from an array a = [1,1,2,3,8,2].

Array.prototype.unique = function(){
    var array = this;
    return array.filter(function(ele, index, arr){
        return index == arr.indexOf(ele);

and in our JavaScript:

var array = [1,1,2,3,8,2];
var uniqueElments = array.unique();

//Output will be 1,2,3,8

But the issue is few of the older version browsers including Internet Explorer 7 that don't support some array features - such as indexOf or filter, so we can use jQuery functionalities like:

  • $.grep instead of Array.filter
    • The $.grep() method removes items from an array as necessary so that all remaining items pass a provided test. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.
  • $.inArray instead of Array.indexOf
    • The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.

Now here's how the changed code would look like:

Array.prototype.unique = function(){
    var array = this;
    return $.grep(array, function(ele, index){
            return $.inArray(ele, array) === index;



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Murali Gowda
Software Developer (Senior)
India India
Yet to be written

You may also be interested in...

Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170525.1 | Last Updated 6 Sep 2013
Article Copyright 2013 by Murali Gowda
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid