Reputation: 541
I'm working on a function that will return the sum of all the purchases the user made.
export async function getBalance(asd) {
const response = await api.get("/compras")
const { data } = response
// customerSuccess.filter(({ id }) => !customerSuccessAway.includes(id))
const userPurchases = data.map((item) => item.userId.includes(asd))
// const userPurchases = data.filter(({ userId }) => !asd.includes(userId))
console.log(userPurchases)
}
The getBalance(id) receives the ID of the user that is logged in. Its type is number, so I cannot use the filter method to filter the array that will be returned in the api call.
The response of the api is and array of objects that contains the 'value' and the 'userId'. What I want is to compare the ID that the function receives and check if there is any purchase made by this id (compare ID with userID) and return the sum of the 'value' of its purchases. Does anyone have an idea on how to do that? I thought about using map or reduce, but couldn't make a solution =(
Upvotes: 0
Views: 82
Reputation: 11915
You can use Array.prototype.filter
to filter the purchases and then use Array.prototype.reduce
to compute the sum of the purchase values.
const userPurchases = data
.filter((purchase) => purchase.userId === asd)
.reduce((sum, purchase) => sum + purchase.value, 0)
And a terse version (although less readable than the first):
const userPurchases = data.reduce(
(sum, purchase) => (purchase.userId === asd ? sum + purchase.value : sum),
0
)
Upvotes: 1
Reputation: 9333
Try this:
// get all the items from the user with the specific id
const filtered = data.filter((item) => item.userId === asd)
// sum all the values for user with the specific id
const totalValue = filtered.reduce((a, b)=>{return a + b.value} ,0)
console.log(totalValue)
``
Upvotes: 0
Reputation: 293
Try this one
customerSuccess.filter((item) => item.userId === asd
Upvotes: 0