0

I need help with multiple filtering array by type: income or outlay, transactions for last month and transactions with value more 1000. I have Buttons Component buttons:

<div className="buttons">
    {buttons.map(item => (
      <button
        variant="outline-primary"
        key={item.id}
        className={item.btnClass}
        type="button"
        onClick={() => {
          filterData(item.type, item.parameter, item.id);
        }}
      >
        {item.label}
      </button>

DATA

transtactions = [{
id: 0,
value: 1000,
type: 'income',
date: new Date(2018, 1, 1)},
{
id: 1,
value: 500,
type: 'outlay',
date: new Date(2019, 1, 2)
},
{
id: 2,
value: 800,
type: 'income',
date: new Date(2019, 0, 3)
},
{
id: 3,
value: 2000,
type: 'outlay',
date: new Date(2019, 1, 4)
},
{
id: 4,
value: 1000,
type: 'income',
date: new Date(2019, 1, 4)
},
{
id: 5,
value: 999,
type: 'income',
date: new Date(2019, 1, 5)
},];

And Buttons

const buttons = [{
       id: 0,
       label: 'income',
       type: 'incomeFilter',
       parameter: 'income',
       btnClass: ''
      },
      {
      id: 1,
      label: 'outlay',
      type: 'outlayFilter',
      parameter: 'outlay',
      btnClass: ''
      },
      {
      id: 2,
      label: 'last month',
      type: 'date',
      parameter: '',
      btnClass: ''
      },
      {
      id: 3,
      label: 'more 1000',
      type: 'value',
      parameter: '1000',
      btnClass: ''
      }];

I can not think of an algorithm for filtering the table using the function. I tried to add additional arrays, but everything worked clumsily

2 Answers 2

1

Kindly try this ::

filterData(type, param, id) {
    let temp = [];
    if (type == 'date') {
      let today = new Date();
      for (let t of transtactions) {
        if (t.date.getMonth() == today.getMonth()) {
          temp.push(t);
        }
      }
    } else if (type == 'value') {
      for (let t of transtactions) {
        if (t.value > 1000) {
          temp.push(t);
        }
      }
    }
    this.setState({
      filteredTransactions: temp
    });
  }

Also i resolved your problem. here is the complete solution.

Sign up to request clarification or add additional context in comments.

Comments

0

When it comes to filtering/sorting arrays, you should make use of Array.prototype.

For example, sorting income from lowest to highest,

filterData = (type, parameter, id) => {
  const sortedArr = this.state.transtactions
                      .filter(transaction => transaction.type === type)
                        .sort(function(a, b) {return a.value - b.value});
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.