Find index in map object using JavaScript

If we want to find index in array of objects, it’s pretty simple. Example below

let a = [
  {prop1:"abc",prop2:"qwe"},
  {prop1:"bnmb",prop2:"yutu"},
  {prop1:"zxvz",prop2:"qwrq"}];
    
let index = a.findIndex(x => x.prop2 ==="yutu");

console.log(index);

I have a map object as shown below

let input = new Map([
    [ 
      "gfg4343434333r",
      { "group": 1, "groupId": "ae027a9e56a2" }
    ],
    [ 
       "5ae027a9e56a2",
        { "group": 2, "groupId": "434346456454" }
    ],
    [ 
        "de027a9e56a2",
        { "group": 3, "groupId": "43343vvfbrrt4445" }
    ],
])

As you can see this map object has a key value pair. suppose I have a input2 as 5ae027a9e56a2 I need to find out which key matches with this input2 and get its position in input. In this case 5ae027a9e56a2 matches with the 2nd element. Once it matches, I want to know the index so that I can go one level above and gets its previous element value.

How do I find the index in map object and how to get to index-1 in such cases? Can someone please shed some light here.?

JavaScript

let input = new Map([
    [ 
      "gfg4343434333r",
      { "group": 1, "groupId": "ae027a9e56a2" }
    ],
    [ 
       "5ae027a9e56a2",
        { "group": 2, "groupId": "434346456454" }
    ],
    [ 
        "de027a9e56a2",
        { "group": 3, "groupId": "43343vvfbrrt4445" }
    ],
]);

let input2 = "5ae027a9e56a2";

let index = Array.from(input.entries()).findIndex(([key]) => key === input2);

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

Access the Previous Element:

  • Once you have the index, you can use array indexing to access the previous element:

JavaScript

let previousElement = Array.from(input.entries())[index - 1];

console.log(previousElement); // Output: ["gfg4343434333r", { group: 1, groupId: 'ae027a9e56a2' }]