Posts

Showing posts from August, 2013

Get unique/distinct values from an array using JQuery $.grep and $.inArray

Consider an example of getting unique elments 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 = arrray.unique(); //Output will be 1,2,3,8 But the issue is few of the older version browsers including IE7 that doesn't support some array features - such as indexOf or filter, so we can use jquery functionalities like:     use $.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. use $.inArray instead of Array.indexOf The $.inArray() method is similar to JavaScript's native .indexOf