Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript Program to Find Index of an Object by Key and Value in an Array
Next article icon

JavaScript Program to Find Index of an Object by Key and Value in an Array

Last Updated : 28 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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()
  • Using a for...of Loop and Object.entries()

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); 

Output
3 

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); 

Output
3 

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); 

Output
1 

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); 

Output
0 

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 

Output
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 

Output
3 

Next Article
JavaScript Program to Find Index of an Object by Key and Value in an Array

G

gauravggeeksforgeeks
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • javascript-array
  • JavaScript-DSA
  • JavaScript-Program
  • Geeks Premier League 2023

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
    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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences