jQuery inArray Method

Hello everyone, Today we will learn, How to find distinct unique elements with in array using jQuery inArray method.

inArray method is used for searching a specified value within an array and it returns its index if found otherwise it will return -1. inArray method is same like .indexOf() method in javascript, which is also return -1 if not any value exists with in array. If the first element within the array matches value, $.inArray() returns 0.

Syntax:

jQuery.inArray( value, array [, fromIndex ] )

value: Input for searching with in array.

array: An array in which to search value.

fromIndex: The index of the array at which to begin the search. The default is 0, which will search the whole array.

document.write([1,2,3,4,5,6].indexOf(1)); // return 0 document.write($.inArray(1,[1,2,3,4,5,6])); // return 0 document.write([1,2,3,4,5,6].indexOf(4)); // return 3 document.write($.inArray(4,[1,2,3,4,5,6])); // return 3 document.write([1,2,3,4,5,6].indexOf(6)); // return 5 document.write($.inArray(6,[1,2,3,4,5,6])); // return 5 document.write([1,2,3,4,5,6].indexOf(0)); // return -1 document.write($.inArray(0,[1,2,3,4,5,6])); // return -1

Lets find distinct element with in array.

Using simple for loop:

var v = [23, 45, 6, 7, 8, 89, 9, 5, 3, 2, 1, 1, 2, 45, 6, 7, 5, 3, 4, 6]; var u = []; for(var c=0; c<v.length; c++){ if($.inArray(v[c],u)==-1) u.push(v[c]); }; console.log(u);

OR

Using forEach method of javascript:

var v = [23, 45, 6, 7, 8, 89, 9, 5, 3, 2, 1, 1, 2, 45, 6, 7, 5, 3, 4, 6]; var u = []; v.forEach(function(ele,indx,arr){ if($.inArray(ele,u)==-1) u.push(ele); }); console.log(u);

OR

Using forEach method with arrow operator:

var v = [23, 45, 6, 7, 8, 89, 9, 5, 3, 2, 1, 1, 2, 45, 6, 7, 5, 3, 4, 6]; var u = []; v.forEach(ele=>{ if($.inArray(ele,u)==-1) u.push(ele); }); console.log(u);

OUTPUT: [23, 45, 6, 7, 8, 89, 9, 5, 3, 2, 1, 4]

Explanation:

We create a new empty array u to get unique elements. Apply loop on array v using for or forEach statement of javascript. find index of each element of array v with in array u using jQuery inArray method. if inArray results -1, i.e. element not exists in array u. we will push that element in array u.

If you have any query or question or topic on which, we might have to write an article for your interest or any kind of suggestion regarding this post, Just feel free to write us, by hit add comment button below or contact via Contact Us form.


Your feedback and suggestions will be highly appreciated. Also try to leave comments from your valid verified email account, so that we can respond you quickly.

 
 

{{c.Content}}

Comment By: {{c.Author}}  On:   {{c.CreatedDate|date:'dd/MM/yyyy'}} / Reply


Categories