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?
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.