Ecosse
Ecosse

Reputation: 35

Index of object in array which has array of one object

I'm working with Google Maps API in Angular (TypeScript). I want to make clickable map of countries, where you click some country it changes color. Seems easy but I'm using ng2-google-maps library for Angular which is a little bit complicated.

My problem: I need to get index of main object in array. But I need to search by value which is in this object as another object in another array.

console.log of those array

I already get country code of clicked region in map. for example "PL" like in this console.log.

I need to get index of main array (PL has '0' index) to check if PL country already exists in this array.

I tried like this:

mainArray.findIndex((result) => result.c.findIndex((result) => result.v === 'PL'));

But it doesn't work. Then I'll need to use probably slice() method to delete found index from main array.

Thank you in advance.

Upvotes: 1

Views: 402

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115282

You are using Array#findIndex within the function which returns index or -1 so it will be falsy in case element is at position 0 and all other cases it will be truthy(non-zero numbers are truthy) so it won't work as you expected.

You can use Array#some method which returns true if condition satisfied for at least one element.

 mainArray.findIndex((result) => result.c.some((result) => result.v === 'PL'));

Upvotes: 2

Related Questions