How to useArray map() and indexOf Methods in Javascript
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
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);
Output
1
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.