1

How can I get Index of a document in an array containing only 1 given matching key: value?

for example if my array is

[
    { name: 'abc', age: 17 },
    { name: 'xyz', age: 18 },
    { name: 'pqr', age: 19 },
]

now how can I get index of first document where age: 18?

I have tried

list.indexOf({ age: 18 })

but this doesn't seem to work, it gives me -1.

1 Answers1

1

You can use Array#findIndex.

const arr = [
    { name: 'abc', age: 17 },
    { name: 'xyz', age: 18 },
    { name: 'pqr', age: 19 },
];
let idx = arr.findIndex(({age})=>age===18);
console.log(idx);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80