我需要按类型提供多个过滤数组的帮助:收入或支出,上个月的交易以及价值超过1000的交易。我有按钮组件按钮:
<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>
数据
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)
},];
和按钮
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: ''
}];
我想不出使用该函数过滤表的算法。我试图添加额外的数组,但一切都很笨拙
请试试这个::
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
});
}
我也解决了你的问题。 here是完整的解决方案。
在过滤/排序数组时,您应该使用Array.prototype。
例如,将收入从最低到最高分类,
filterData = (type, parameter, id) => {
const sortedArr = this.state.transtactions
.filter(transaction => transaction.type === type)
.sort(function(a, b) {return a.value - b.value});
}