JavaScript Program to Find Index of an Object by Key and Value in an Array
Last Updated :
28 Jun, 2024
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.
So let's see each of the approaches with its implementation.
Approach 1: Using JavaScript for Loop and If Condition
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.
JavaScript
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);
Approach 2: Using findIndex() Method
In this approach, we use the findIndex() method. As this method is searching for the object in the array and it returns the index of the first matched object. Here, we are giving the key and the value and checking for the match.
Syntax
array.findIndex(callback(element[, index[, array]])[, thisArg])
Example: In this example, we will find an index of an object by key and value in a JavaScript array using the findIndex() Method.
JavaScript
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 = objArray.findIndex(
(temp) => temp[k] === val
);
console.log(objIndex);
Approach 3: Using Array map() and indexOf Methods
In this approach, we are using the map() method to go through the input elements and we are giving the match condtion of key and value. There is indexOf() method, which returns the index of the first matched elements. We are storing this index in the objIndex variable and printing it using log function.
Syntax
map((element, index, array) => { /* … */ })
Example: In this example, we will find the index of an object by key and value in a JavaScript array using Using map() and indexOf Methods
JavaScript
let objArray = [
{ course: "DevOps", price: 11999 },
{ course: "GATE", price: 6999 },
{ course: "ML & DS", price: 5999 },
{ course: "DSA", price: 3999 },
];
let k = "course";
let val = "GATE";
let objIndex = objArray.map((temp) => temp[k]).indexOf(val);
console.log(objIndex);
Approach 4: Using Array some() Method
In this method, we use the some() method that is used to check whether one of the object from the array satisfies the condtion specified in the argument method. Here, we are checking the condtion of key==value, and then we are returning the index of that value and storing in the varibale and printing using console.log() method.
Syntax
array.some(callback(element,index,array),thisArg)
Example: In this example, we will find an index of an object by key and value in a JavaScript array Using some() Method
JavaScript
let objArray = [
{ course: "DevOps", price: 11999 },
{ course: "GATE", price: 6999 },
{ course: "ML & DS", price: 5999 },
{ course: "DSA", price: 3999 },
];
let k = "course";
let val = "DevOps";
let objIndex;
objArray.some((key, value) => {
if (key.course == val) {
objIndex = value;
return true;
}
});
console.log(objIndex);
Approach 5: Using Array.reduce()
Using Array.reduce(), the function iterates through the array, accumulating an index where the object's specified key matches the given value. If found, it returns the index; otherwise, it returns -1, indicating the object was not found.
Syntax:
array.reduce( function(total, currentValue, currentIndex, arr),
initialValue )
Example: In this example The findIndexByKeyValue function searches an array of objects for a specific key-value pair and returns the index of the first matching object.
JavaScript
function findIndexByKeyValue(arr, key, value) {
return arr.reduce((index, obj, i) => (obj[key] === value ? i : index), -1);
}
let array = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }];
let index = findIndexByKeyValue(array, 'name', 'Bob');
console.log(index); // 1
Approach 6: Using a for...of Loop and Object.entries()
In this approach, we utilize the for...of loop combined with Object.entries() to find the index of an object by key and value in an array. This method iterates over the array elements and uses Object.entries() to get an array of key-value pairs from the object. We then check if the object contains the specified key and if its value matches the given value.
Example: In this example, we will find the index of an object by key and value in a JavaScript array using the for...of loop and Object.entries().
JavaScript
const arr = [
{ course: "DevOps", price: 11999 },
{ course: "GATE", price: 6999 },
{ course: "ML & DS", price: 5999 },
{ course: "DSA", price: 3999 },
];
const key = "course";
const value = "DSA";
let index = -1;
for (const [i, element] of arr.entries()) {
for (const [k, v] of Object.entries(element)) {
if (k === key && v === value) {
index = i;
break;
}
}
if (index !== -1) {
break;
}
}
console.log(index); // Output: 3
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read