Unique Elements filter on array in jQuery
When you want to find out unique elements from the list of Javascript array, there is one easy way to do it through jQuery. Most of the users do this by doing "for loop" in javascript which is very old approach to follow, but jQuery has one method which gives the Unique Values from the Javascript array which is very simple and easy to use.
Here is how you can find out the Unique Values from Javascript Array in jQuery:
1. Declare Javascript array as given below:
var num=[10, 20, 30, 10, 40, 20, 60];
2. Write a jQuery method to filter the array to find Unique elements:
- num = $.grep(num, function(elm, idx){
- return idx == num.indexOf(elm)
- });
3. Finally Print the values of "num" array:
console.log("Unique Numbers: "+ num);
Output:
Unique Numbers: 10,20,30,40,60
What is $.grep method in jQuery:
$.grep() method returns the list of elements which passes the condition mentioned in $.grep() function, but it does not change the original array. To apply the filter changes to the original array, you need to assign the filter result to original array as shown in the above example.
The first parameter of this function is the array which you need to pass.
Second parameter is "function(element, index)": element parameter in the function is the element from the array passed to $.grep(). Index parameter is the index of the element in the passed array.
$.grep() function will loop through each array element one by one. With the help of this, you can format the array by using element & index values passed in the second parameter which is "function(element, index)". You can assign filtered result either to original array or you can create new array and pass to it.