How to filter from two different arrays in react-native?

ぐ巨炮叔叔 提交于 2020-11-29 19:50:09

问题


I need to display a history of expenses grouped using month and each month header should display the total expense of that month. I want a SectionList to display each months expenses and I'm using react-native firebase to store the data. But how do I filter the transactions based on month and display it under corresponding month header?

    componentDidMount() {
    //Querying
    firestore()
      .collection('expenses')
      .orderBy('dateTime', 'desc')
      .get()
      .then((querySnapshot) => {
        const expenses = [];
        querySnapshot.forEach((documentSnapshot) => {
          console.log('documentordered', documentSnapshot.data());
          expenses.push({...documentSnapshot.data(), key: documentSnapshot.id});
        });

        const expenseData = expenses.map((item) => ({
          title: moment(item.dateTime).format('MMMM'),
          data: this.filterExpenses(expenses),
        }));
        // this.setState({expenseHistory: expenses}, () => {
        // });
      });
  }

filterExpenses(expenses) {
    var filtered = expenses.filter((item) =>
      monthNames.forEach((element) => {
        element == moment(item.dateTime).format('MMMM');
      }),
    );

    console.log('keys', filtered); //Getting output as "keys", []
  }

createCollection = () => {
    Keyboard.dismiss();
    firestore()
      .collection('expenses')
      .add({
        expenseNote: this.state.expenseNote,
        expenseValue: this.state.expenseValue,
        category: this.state.category,
        dateTime: moment().format(),
      })
      .then(() => {
        this.setState({
          expenseNote: '',
          expenseValue: '',
          category: '',
          dateTime: '',
        });
      });
  };

This is my expense data and month details.

const monthNames = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December',
];

const expenses = [
  {
    category: 'Home',
    dateTime: '2020-11-25T12:08:08+05:30',
    expenseNote: 'abc',
    expenseValue: 200,
    key: 'm0NSjh78vl3lLdXz7tlE',
  },
  {
    category: 'Shopping',
    dateTime: '2020-10-25T18:47:08+05:30',
    expenseNote: 'Shop',
    expenseValue: 123,
    key: 'K3xcuRAD83B15I4mBYnK',
  },
  {
    category: 'Travel',
    dateTime: '2020-10-25T12:47:08+05:30',
    expenseNote: 'Uber',
    expenseValue: 100,
    key: 'M0Qbwtzz5mzQzo3N4b9e',
  },
  {
    category: 'Home',
    dateTime: '2020-10-25T12:08:08+05:30',
    expenseNote: 'Hotel',
    expenseValue: 300,
    key: 'aXocTlJlCvJTl5w5MREr',
  },
];

来源:https://stackoverflow.com/questions/64525341/how-to-filter-from-two-different-arrays-in-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!