我正在使用lodash进行一些过滤。
我具有以下功能:
filterByCardinalPoint = (key, value) => {
const { passengersData } = this.props;
console.log('passengersData', passengersData);
return filter(passengersData, [key, value]);
};
callFilter = () => {
passengersGoingNorth = this.filterByCardinalPoint('cardinalpoint', 'N')
.length;
passengersGoingSouth = this.filterByCardinalPoint('cardinalpoint', 'S')
.length;
passengersGoingWest = this.filterByCardinalPoint('cardinalpoint', 'W')
.length;
passengersGoingEast = this.filterByCardinalPoint('cardinalpoint', 'E')
.length;
};
我正在render方法中调用callFilter
。该功能被调用约8次。我该如何优化它才能调用一次?
答案 0 :(得分:2)
由于您需要各个方向的人数,因此可以将_.countBy()
与_.property()
一起使用。分解结果对象以将数字分配给变量。
示例:
const { countBy, property } = _;
let passengersGoingNorth, passengersGoingSouth, passengersGoingWest, passengersGoingEast;
const passengersData = [{ cardinalpoint: 'N' }, { cardinalpoint: 'N' }, { cardinalpoint: 'S' }, { cardinalpoint: 'N' }, { cardinalpoint: 'E' }];
({
N: passengersGoingNorth = 0,
S: passengersGoingSouth = 0,
W: passengersGoingWest = 0,
E: passengersGoingEast = 0
} = countBy(passengersData, property('cardinalpoint')));
console.log(passengersGoingNorth, passengersGoingSouth, passengersGoingWest, passengersGoingEast); // 3, 1, 0, 1
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
答案 1 :(得分:1)
那也许太老套了,但是一个简单的for
循环呢:
for(const { cardinalpoint } of passengersData) {
if(cardinalpoint === "N")
passengersGoingNorth++;
if(cardinalpoint === "S")
passengersGoingSouth++;
if(cardinalpoint === "E")
passengersGoingEast++;
if(cardinalpoint === "W")
passengersGoingWest++;
}
如果这太重复了,只需将方向用作查找键:
const directions = { N: 0, S: 0, W: 0, E: 0 };
for(const passenger of passengersData)
directions[ passenger.cardinalpoint ]++;
然后,您可以将乘客以directions.S
的身分带到南方。