Navid777
Navid777

Reputation: 3681

how to access the element in a jQuery filter function?

I have an array like this:

x=[{id:1}, {id:2}]

and I want to access the id of the element in a filter function :

x.filter(function(index) {
   if( x[index]['id'] == 1)
       return true;
   return false;
}

but is says x[index] is undefined

what should I do to access x[index] in filter function?

Upvotes: 2

Views: 553

Answers (5)

R D
R D

Reputation: 1332

.filter ([Array.prototype.filter][1]) calls the supplied function with 3 arguments:

function(element, index, array) {
    ...
  • element is the particular array element for the call.
  • index is the current index of the element
  • array is the array being filtered.

You can use any or all of the arguments.

In your case, i refers to the element and is used in the body of your function:

function(i){
    return (i > 2);
}

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

If you only pass one parameter, then that parameter points to item and not index. You need to use index.id==1 instead of x[index]['id'] == 1:

x.filter(function(index) {
 if(index.id == 1)
   return true;
   return false;
}

Working Demo

Upvotes: 1

sameer
sameer

Reputation: 320

Please check with the below code

x = x.filter(function(item) {
   if( item.id == 1)
       return true;
   return false;
});

Upvotes: -1

Xlander
Xlander

Reputation: 1331

You can add another argument for the current element.

x.filter(function(elmt, index){
 if( elmt['id'] == 1)
   return true;
 return false;
});

Upvotes: 0

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

You have to do like this:

x.filter(function(item,index) {

   if( item.id == 1)
       return true;
   return false;
});

The first parameter is item of array and second parameter is the index of array.

FIDDLE:

http://jsfiddle.net/r1e4p1eo/1/

Upvotes: 2

Related Questions