1

I have two array of objects. I want to get the index of matched element from array 2. How to find that?

This is an example.

Array 1

selectedProduct: [{id:2, name:"product 1", category:"home"}]

Array 2

allProducts: [{id:1, name:"product 3", category:"grocery"},
             {id:2, name:"product 1", category:"home"},{id:3, name:"product 4",category:"vegetables"}]

Code snippet:

const index = this.allProducts.findIndex(item => this.selectedproduct.filter(entry => entry.id === item.id))

But, it is returning 0. How can i get the index of matched element?

2
  • 1
    Change filter to some Commented Sep 27, 2020 at 10:38
  • @user7411584 please mark the answer as the solution if it solved the problem so future visitors can benefit from it as well. Commented Sep 27, 2020 at 18:23

1 Answer 1

2

Use some instead:

let selectedProduct = [
  {id:2, name:"product 1", category:"home"}
];
let allProducts = [
  {id:1, name:"product 3", category:"grocery"},
  {id:2, name:"product 1", category:"home"},
  {id:3, name:"product 4",category:"vegetables"}
]

const index = allProducts.findIndex(item => selectedProduct.some(entry => entry.id === item.id));

console.log(index);

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

2 Comments

While this does technically work, that's not the purpose of find, which returns the first matching element or undefined. some is more appropriate since it returns a boolean true even if the element found is falsy.
@PatrickRoberts thanks for the comment. Yes some is better for this case.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.