在对象数组内按范围过滤

时间:2020-09-24 06:59:10

标签: javascript arrays object ecmascript-6 filter

我想做一个班次解析器助手,它是产生班次的时间,下面是班次规则

  let shift_rule = [
    {
      shift: '07-12',
      start: 7,
      finish: 12
    },
    {
      shift: '12-17',
      start: 12,
      finish: 17
    },
    {
      shift: '17-22',
      start: 17,
      finish: 22
    },
  ];

如果时间偏移为timeStart = 7,则timeFinish = 17

预期输出:

[
    {
      shift: '07-12',
      start: 7,
      finish: 12
    },
    {
      shift: '12-17'
      start: 12,
      finish: 17
    },
]

我已经尝试用此代码解决

shift_rule
    .map((time) => ((timeFinish > time.start)) && time)
    .filter(item => typeof item !== 'boolean');

但是当过滤器为time.start = 17timeFinish = 22时,它会显示:

[
    {
      shift: '07-12',
      start: 7,
      finish: 12
    },
    {
      shift: '12-17',
      start: 12,
      finish: 17
    },
    {
      shift: '17-22',
      start: 17,
      finish: 22
    },
  ]

希望可以通过ES6 Functional解决

1 个答案:

答案 0 :(得分:2)

您可以通过检查每个范围的开始是否在另一个范围的结束之前来检查重叠的时间范围(例如,参见this question)。您可以在过滤器中实现该代码,然后使用map仅返回班次名称:

let shift_rule = [
  { shift: '07-12', start: 7, finish: 12 },
  { shift: '12-17', start: 12, finish: 17 },
  { shift: '17-22', start: 17, finish: 22 } 
];

const filter_shifts = (rules, timeStart, timeFinish) =>
  rules.filter(s => s.start < timeFinish && s.finish > timeStart).map(s => s.shift);

console.log(filter_shifts(shift_rule, 7, 17));
console.log(filter_shifts(shift_rule, 17, 22));