简体   繁体   中英

How to filter array with only purchases made by user

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 =(

api response: api响应

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
)

Try this one

customerSuccess.filter((item) => item.userId === asd

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) 
``

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM