简体   繁体   English

在数组中查找唯一属性并计算匹配项

[英]Find unique properties in array and calculate matching items

I want to find matching items in this array using the property category , in this app each user can have custom categories so the server cannot know the name of categories prior to running the function.我想使用属性category在这个数组中找到匹配的项目,在这个应用程序中,每个用户都可以有自定义类别,所以服务器在运行 function 之前无法知道类别的名称。

0: {amount: "123", category: "drinks", location: "NYC", note: "piano bar", receipt: "img.jpg", …}
1: {amount: "123", category: "drinks", location: "NYC", note: "piano bar", receipt: "img.jpg", …}
2: {amount: "123", category: "bills", location: "NYC", note: "piano bar", receipt: "img.jpg", …}
3: {amount: "123", category: "savings", location: "NYC", note: "piano bar", receipt: "img.jpg, ...}

This my code so far到目前为止这是我的代码

fetch = () => {
    this.setState({ loading: true });
    const { currentUser } = fire.auth();
    var stamp = moment().format('LLLL');
    const wallet = fire.database().ref(`/master/${currentUser.uid}/wallets/cash/income/transactions/20190520`);
    wallet.on('value', snapshot => {
      var data = snapshot.val();
      var categories = []
      for (let i in data) {
        categories.push(data[i].category)
      };
      console.log(categories);
      this.setState({ loading: false, ok: true });
    })
  }

Here my goal is find all categories in this array and store them in value like {drinks,bills,savings} and then see how many items match this category like在这里,我的目标是找到这个数组中的所有类别并将它们存储在{drinks,bills,savings}之类的值中,然后查看有多少项目与此类别匹配

  • drinks 2饮料 2
  • bills 1账单 1
  • savings 1储蓄 1

You could use reduce to get all categories with a count of the number of array elements associated with each one.您可以使用reduce来获取所有类别,并计算与每个类别关联的数组元素的数量。

 const arr = [{ amount: "123", category: "drinks", location: "NYC", note: "piano bar", receipt: "img.jpg" }, { amount: "123", category: "drinks", location: "NYC", note: "piano bar", receipt: "img.jpg" }, { amount: "123", category: "bills", location: "NYC", note: "piano bar", receipt: "img.jpg" }, { amount: "123", category: "savings", location: "NYC", note: "piano bar", receipt: "img.jpg" }]; const categories = arr.reduce((acc, obj) => { const category = obj.category; if (category in acc) { acc[category] += 1; } else { acc[category] = 1; } return acc; }, {}); console.log(categories); // { drinks: 2, bills: 1, savings: 1 }

you can use Es6 Map class to store key as category and value as array of matching element.您可以使用 Es6 Map class 将键存储为类别,将值存储为匹配元素的数组。 Map provides plenty of methods as well that you can check here Map也提供了很多方法,你可以在这里查看

let yourArray = [{
        amount: "123",
        category: "drinks",
        location: "NYC",
        note: "piano bar",
        receipt: "img.jpg"
    },
    {
        amount: "123",
        category: "drinks",
        location: "NYC",
        note: "piano bar",
        receipt: "img.jpg"
    },
    {
        amount: "123",
        category: "bills",
        location: "NYC",
        note: "piano bar",
        receipt: "img.jpg"
    },
    {
        amount: "123",
        category: "savings",
        location: "NYC",
        note: "piano bar",
        receipt: "img.jpg"
    }
]


var newMap = new Map();


yourArray.forEach(ele => {
    if (!newMap.get(ele.category)) {
        newMap.set(ele.category, [ele])
    } else {
        newMap.get(ele.category).push(ele)
    }
})

console.log(newMap)
newMap.forEach((value, key) => {
    console.log(`${key} ${value.length}`)
})

you can try using the for each loop and iterate over them and save the count in an object您可以尝试使用 for each 循环并遍历它们并将计数保存在 object 中

    let data = [
{amount: "123", category: "drinks", location: "NYC", note: "piano bar", receipt: "img.jpg"},
{amount: "123", category: "drinks", location: "NYC", note: "piano bar", receipt: "img.jpg"},
{amount: "123", category: "bills", location: "NYC", note: "piano bar", receipt: "img.jpg"},
{amount: "123", category: "savings", location: "NYC", note: "piano bar", receipt: "img.jpg"}];

let countObj = {};
data.forEach((val,ind)=>{
    if(countObj[val.category]){
        countObj[val.category] = countObj[val.category] + 1 ;
  }else{
    countObj[val.category] = 1;
  }
})
console.log(countObj);

gives the result给出结果

bills: 1
drinks: 2
savings: 1

You could use array.includes to see if your value already exists, and count the amount in another array like this:您可以使用 array.includes 查看您的值是否已经存在,并计算另一个数组中的数量,如下所示:

 fetch = () => {
        this.setState({ loading: true });
        const { currentUser } = fire.auth();
        var stamp = moment().format('LLLL');
        const wallet = fire.database().ref(`/master/${currentUser.uid}/wallets/cash/income/transactions/20190520`);
        wallet.on('value', snapshot => {
          var data = snapshot.val();
          var categories = [];
          var amounts = [];
          for (let i in data) {
            if(categories.includes(data[i].category){
                if(amounts[data[i].category] == undefined){
                   amounts[data[i].category]=1;
                }else{
                   amounts[data[i].category]++;
                }
            }
            categories.push(data[i].category)
          };
          console.log(amounts);
          this.setState({ loading: false, ok: true });
        })
      }

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

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