【问题标题】:How do I filter data with proper algorithm?如何使用适当的算法过滤数据?
【发布时间】: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


【解决方案1】:

您可以获取一组键/索引并使用 Array#some 进行迭代

const
    result = tickets.filter(item => 
        stops.mainCheckBox ||
        Object.keys(stops.checkBox).some(i =>
            stops.checkBox[i] &&
            item.segments[0].stops.length === +i &&
            item.segments[1].stops.length === +i
        )
    );

【讨论】:

  • 感谢帮助!我在想groupBy 函数,它将对象的键作为停止数,例如:{0: [items with 0 length of both stops], 1: [items with 1 length of both stops]}。但不是来自 lodash,有什么想法可以这样分组吗?
猜你喜欢
  • 1970-01-01
  • 2010-10-19
  • 2019-03-17
  • 2015-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-26
相关资源
最近更新 更多