Reputation: 1401
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?
Upvotes: 1
Views: 959
Reputation: 28424
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);
Upvotes: 2