How to get index of object inside an array that matches the condition in jQuery ?
jQuery is a free and open-source JavaScript library designed to add interactivity to the HTML web pages. jQuery is similar to JavaScript in terms of functionality but what makes it popular is its simplicity and ease of use. jQuery comes bundles with inbuilt methods that help achieve the desired output. In this article, we will discuss the two methods in jQuery that can be used to get the index of an object inside an array that matches the given condition. The two methods are discussed as follows.
- findIndex(): This method executes the function passed as a parameter for each element present in the array.
- some(): The arr.some() method checks whether at least one of the elements of the array satisfies the condition checked by the argument method.
Approach 1: In the first approach, we show the procedure for finding the index of an object in an array that matches a given condition using the findIndex() method of jQuery. The findIndex() method takes a function as the first parameter. This function is executed on every element of the array and the element for which the function returns “true” is the one that matched the specified condition. Thus the index of this matched element is stored in the index variable. The value of the index variable is returned to the console. Similarly, for the index1 variable, there is more than one object having age=”20″. In this situation, the index of the first matched object is returned. If no match is present then the output is -1.
var arr = [
{ name: "ram" , age: "20" },
{ name: "sam" , age: "20" },
{ name: "tom" , age: "19" },
{ name: "harry" , age: "19" }
];
var index;
arr.findIndex( function (entry, i) {
if (entry.name == "tom" ) {
index = i;
return true ;
}
});
index1 = arr.findIndex(x => x.age === "20" );
console.log(index);
console.log(index1);
|
Output:
2
0
Approach 2: In the second approach, we show the procedure for finding the index of an object in an array that matches a given condition using the some() method of jQuery. The some() method takes a function as the first parameter. This function is executed on every element of the array and the element for which the function returns “true” is the one that matched the specified condition. Thus the index of this matched element is stored in the index variable. The value of the index variable is returned to the console.
var arr = [
{ name: "ram" , age: "20" },
{ name: "sam" , age: "21" },
{ name: "tom" , age: "19" },
{ name: "harry" , age: "19" }
];
var index;
arr.some( function (entry, i) {
if (entry.name == "tom" ) {
index = i;
return true ;
}
});
console.log(index);
|
Output:
2
Last Updated :
15 Oct, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...