how to search index of a object in javascript array

To search for the index of an object in a JavaScript array, you can use the findIndex() method or a for loop with conditional statements. Here are examples using both methods:


  Method 1: Using findIndex()
  const myArray = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 3, name: 'Charlie'}];

  const searchObject = {id: 2, name: 'Bob'};
  
  const index = myArray.findIndex(obj => obj.id === searchObject.id && obj.name === searchObject.name);
  
  console.log(index); // Output: 1        
 Method 2: Using for loop with conditional statements
  
  const myArray = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 3, name: 'Charlie'}];
  
const searchObject = {id: 2, name: 'Bob'};

let index = -1;
for (let i = 0; i < myArray.length; i++) {
  if (myArray[i].id === searchObject.id && myArray[i].name === searchObject.name) {
    index = i;
    break;
  }
}

console.log(index); // Output: 1        

To view or add a comment, sign in

More articles by Deepak Prajapat

  • Avoid new keyword

    NOTE : Using the new keyword makes your program slower

  • tailwind css grid items width and height

    You can use the `w-{width}` and `h-{height}` classes in Tailwind CSS to set the width and height of grid items. For…

  • toString() Parameters

    Some toString() functions take parameters, most notably numbers, and Node.js buffers.

  • Frontend Developer Application for [Company Name]

    Sure! Here's an example email you can use as a guide: Dear [Hiring Manager's Name], I am writing to express my interest…

  • How to check typing speed with javascript code

    To type 100 words in 1 minute with JavaScript code, you can use a simple formula based on the number of words, start…

Explore content categories