How to useJavaScript for Loop and If Condition in Javascript
In this approach, we are using the for loop and if condition to get the index of the object. Here, firstly we take the input of key and value and then we iterate over the array, by using the if condition we are checking if the key and value are been matched in the array. For example. {course: DSA} is matched, then we return its index and print the output, else if no match is found then -1 is printed.
Syntax
for (statement 1; statement 2; statement 3) {
code here...
}
Example: In this example, we will find an index of an object by key and value in a JavaScript array using Using for Loop and if Condition.
let objArray = [
{ course: "DevOps", price: 11999 },
{ course: "GATE", price: 6999 },
{ course: "ML & DS", price: 5999 },
{ course: "DSA", price: 3999 },
];
let k = "course";
let val = "DSA";
let objIndex = -1;
for (let i = 0; i < objArray.length; i++) {
if (objArray[i][k] === val) {
objIndex = i;
break;
}
}
console.log(objIndex);
Output
3
JavaScript Program to Find Index of an Object by Key and Value in an Array
Finding the index of an object by key and value in an array involves iterating through the array and checking each object’s key-value pair. Once a match is found, its index is returned. If no match is found, -1 is returned.
Example:
arr = [ { course: "DevOps", price: 11999 }, { course: "GATE", price: 6999 }, { course: "ML & DS", price: 5999 }, { course: "DSA", price: 3999 }, ]; Input: key = "course"; value = "DSA"; Output: 3 Explanation: name : DSA object is at 3rd index in the array.
Table of Content
- Using JavaScript for Loop and If Condition
- Using findIndex() Method
- Using Array map() and indexOf Methods
- Using Array some() Method
- Using Array.reduce()
So let’s see each of the approaches with its implementation.