Here is my sample data
const data = [{"amount": "600,000", "cover": null, "id": "1", "img": "636e56de36301.1.png", "make": "bmw", "model": "bmw", "name": "APA", "policy": "Motor Insurance", "rate": "6"}, {"amount": "300,000", "cover": null, "id": "2", "img": "63723574a81ce.1.png", "make": "ferrari", "model": "ferrari", "name": "CIC", "policy": "Motor Insurance", "rate": "3"}, {"amount": "450,000", "cover": null, "id": "3", "img": "63723726cb1df.1.png", "make": "audi", "model": "audi", "name": "Mayfair Insurance", "policy": "Motor Insurance", "rate": "4.5"}]
const id = [‘3’]
and here is the code am using to return the array for id 3.
const provider = AllProvider.reduce((prv, item) => {
if(id.includes(item.id)){
return prv
}
return prv
})
console.log('This is provider' ,provider)
Unfortunately, the return am getting is data with an id of 1
Output:
This is provider {"amount": "600,000", "cover": null, "id": "1", "img": "636e56de36301.1.png", "make": "bmw", "model": "bmw", "name": "APA", "policy": "Motor Insurance", "rate": "6"}
can someone tell what am doing wrong please
>Solution :
If your intention is to return only an object you can use reduce() but currently, you’re doing it a little bit wrong way.
- You need to pass an initial value to the
reduce()if it’s not then thereducepicks the first element of the array as the initial value and starts iterating from the second element. so when condition(s) are false it returns the first element of the array. so you need to be careful with it. - You need to return
itemhereif(id.includes(item.id)) return itemnotprev.
Here is the solution with .reduce()
const data = [{"amount": "600,000", "cover": null, "id": "1", "img": "636e56de36301.1.png", "make": "bmw", "model": "bmw", "name": "APA", "policy": "Motor Insurance", "rate": "6"}, {"amount": "300,000", "cover": null, "id": "2", "img": "63723574a81ce.1.png", "make": "ferrari", "model": "ferrari", "name": "CIC", "policy": "Motor Insurance", "rate": "3"}, {"amount": "450,000", "cover": null, "id": "3", "img": "63723726cb1df.1.png", "make": "audi", "model": "audi", "name": "Mayfair Insurance", "policy": "Motor Insurance", "rate": "4.5"}]
const id = ['3'];
const provider = data.reduce((prv, item) => {
if(id.includes(item.id)){
return item
}
return prv
}, {});
console.log(provider);
Also You can use .filter()
const data = [{"amount": "600,000", "cover": null, "id": "1", "img": "636e56de36301.1.png", "make": "bmw", "model": "bmw", "name": "APA", "policy": "Motor Insurance", "rate": "6"}, {"amount": "300,000", "cover": null, "id": "2", "img": "63723574a81ce.1.png", "make": "ferrari", "model": "ferrari", "name": "CIC", "policy": "Motor Insurance", "rate": "3"}, {"amount": "450,000", "cover": null, "id": "3", "img": "63723726cb1df.1.png", "make": "audi", "model": "audi", "name": "Mayfair Insurance", "policy": "Motor Insurance", "rate": "4.5"}]
const id = ['3'];
console.log(data.filter(it => id.includes(it.id)));