How can I find the index of a 2d array of objects in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

To find the index of a two-dimensional array of objects, use two for loops, one for row and another for column. Following is the code −

Example

function matrixIndexed(details, name) {
   var r;
   var c;
   for (r = 0; r < details.length; ++r) {
      const nsDetails = details[r];
      for (c = 0; c < nsDetails.length; ++c) {
         const tempObject = nsDetails[c];
         if (tempObject.studentName === name) {
            return { r, c};
         }
      }
   }
   return {};
}
const details = [
   [
      {studentName: 'John'}, {studentName:'David'}
   ],
   [
      {studentName:"Mike"},{studentName:'Bob'},{studentName:'Carol'}
   ]
];
var {r, c } = matrixIndexed(details, 'Bob');
console.log(r, c);

To run the above program, you need to use the following command −

node fileName.js.

Output

Here, my file name is demo160.js. This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo160.js
1 1
raja
Published on 12-Sep-2020 11:18:16
Advertisements