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.

0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments