【发布时间】:2021-02-22 08:45:41
【问题描述】:
所以我有这些代码块:
const stops = {
mainCheckBox : true,
checkBox: {
0: true,
1: true,
2: true,
3: true
}
}
const tickets = [
{
segments: [
{
stops: ['QWE', 'RTY', 'BGT']
},
{
stops: ['CVB']
}
]
},
... // plus other same objects
]
我需要什么?我需要根据停靠点的长度+适当的复选框来过滤它们。例如:如果我有 chekcBox[0] true 并且两个停止数组的长度为 0,那么我返回该项目。
所以我写了那个算法:
const result = tickets.filter(item => {
if (stops.mainCheckBox) return item
if (stops.checkBox[0] && item.segments[0].stops.length === 0 && item.segments[1].stops.length === 0) return item
if (stops.checkBox[1] && item.segments[0].stops.length === 1 && item.segments[1].stops.length === 1) return item
if (stops.checkBox[2] && item.segments[0].stops.length === 2 && item.segments[1].stops.length === 2) return item
if (stops.checkBox[3] && item.segments[0].stops.length === 3 && item.segments[1].stops.length === 3) return item
})
但该代码看起来很糟糕且无法接受。那么如果没有其他库(如 lodash 等),我该如何重构算法?
【问题讨论】:
-
顺便说一句,过滤器不将返回值作为映射结果,它采用一个代表布尔值的值,这将过滤项目与否。顺便说一句,为什么只有
item.segments[0]和item.segments[1]很有趣?item.segments[n]会发生什么? -
@Nina Scholz,别提了,段中只有 2 个停靠点数组
标签: javascript reactjs filter