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
How to get a key in a JavaScript object by its value ? To get a key in a JavaScript object by its value means finding the key associated with a specific value in an object. Given an object with key-value pairs, you want to identify which key corresponds to a particular value, often for searching or data retrieval.How to get a key in a JavaScript object
4 min read
JavaScript Get the index of an object by its property Given an object, the task is to get the object's index from the array of objects of the given property name and property value using JavaScript. we're going to discuss a few techniques. Below are the following approaches: Table of Content Using Array map() MethodUsing for loopUsing findIndex() Metho
3 min read
JavaScript indexOf() method in an Object Array In JavaScript, indexOf() methods provide the first index at which the given element exists, and -1 in case it is not present in the array. Syntax: indexOf(element)indexOf(element, start);Parameters: element: the element to be searched in the input arraystart: the index from which the search has to b
2 min read
Javascript Program for Search an element in a sorted and rotated array An element in a sorted array can be found in O(log n) time via binary search. But suppose we rotate an ascending order sorted array at some pivot unknown to you beforehand. So for instance, 1 2 3 4 5 might become 3 4 5 1 2. Devise a way to find an element in the rotated array in O(log n) time. Exam
7 min read
Java Program to Access All Data as Object Array Java is an object-oriented programming language. Most of the work is done with the help of objects. We know that an array is a collection of the same data type that dynamically creates objects and can have elements of primitive types. Java allows us to store objects in an array. In Java, the class i
4 min read
How to get the Value by a Key in JavaScript Map? JavaScript Map is a powerful data structure that provides a convenient way to store key-value pairs and retrieve values based on keys. This can be especially useful when we need to associate specific data with unique identifiers or keys.Different Approaches to Get the Value by a Key in JavaScript Ma
3 min read
Binary search in an object Array for the field of an element What is Binary Searching?Binary searching is a type of algorithm that can quickly search through a sorted array of elements. The algorithm works by comparing the search key to the middle element of the array. If the key is larger than the middle element, the algorithm will search the right side of t
8 min read
How to Find Length or Size of an Array in Java? Finding the length of an array is a very common and basic task in Java programming. Knowing the size of an array is essential so that we can perform certain operations. In this article, we will discuss multiple ways to find the length or size of an array in Java.In this article, we will learn:How to
3 min read
How to find the index of an element in an array using PHP ? In this article, we will discuss how to find the index of an element in an array in PHP. Array indexing starts from 0 to n-1. Here we have some common approachesTable of ContentUsing array_search() FunctionUsing array_flip()Using a custom functionUsing a foreach LoopUsing array_keys FunctionUsing ar
6 min read
How to Convert Two Arrays Containing Keys and Values to HashMap in Java? HashMap is part of the Collections framework of java. It stores the data in the form of key-value pairs. These values of the HashMap can be accessed by using their respective keys or the key-value pairs can be accessed using their indexes (of Integer type). HashMap is similar to Hashtable in java. T
2 min read