简体   繁体   English

如何过滤仅由用户购买的数组

[英]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.我正在研究 function ,它将返回用户购买的所有商品的总和。

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. getBalance(id) 接收登录用户的 ID。它的类型是数字,所以我不能使用过滤器方法过滤将在 api 调用中返回的数组。

The response of the api is and array of objects that contains the 'value' and the 'userId'. api 的响应是包含“值”和“用户 ID”的对象数组。 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.我想要的是比较 function 收到的 ID 并检查此 ID 是否进行了任何购买(将 ID 与用户 ID 进行比较)并返回其购买的“价值”总和。 Does anyone have an idea on how to do that?有谁知道如何做到这一点? I thought about using map or reduce, but couldn't make a solution =(我想过使用 map 或减少,但无法解决=(

api response: api 响应: 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.您可以使用Array.prototype.filter过滤购买,然后使用Array.prototype.reduce计算购买值的总和。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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