【问题标题】:array.filter() and array.some() not acting as expected with an '||' conditionarray.filter() 和 array.some() 没有按预期使用 '||'健康)状况
【发布时间】:2020-12-07 02:45:48
【问题描述】:

这是一个工作示例(here 是指向您可以玩的东西的链接):

  var idDateArray = [
  {
    id: '1',
    updateTime: '00:00:00.000Z',
    updateDate: '2019-01-01'
  },
  {
    id: '2',
    updateTime: '00:00:00.000Z',
    updateDate: '2021-01-01'
  },
  {
    id: '3',
    updateTime: '00:00:00.000Z',
    updateDate: '2019-01-01'
  },
  {
    id: '4',
    updateTime: '00:00:00.000Z',
    updateDate: '2019-01-01'
  },
  {
    id: '5',
    updateTime: '00:00:00.000Z',
    updateDate: '2020-01-01'
  }
]

var itemArray = [
      {
        updateDate: '2020-01-01',
        updateTime: '00:00:00.000Z',
        id: '4'
      },
      {
        updateDate: '2020-01-02',
        updateTime: '00:00:00.000Z',
        id: '2'
      },
      {
        updateDate: '2021-01-02',
        updateTime: '00:00:00.000Z',
        id: '3'
      },
      {
        updateDate: '2020-01-01',
        updateTime: '00:00:00.000Z',
        id: '1'
      }
    ]
 
 var filteredArray = idDateArray.filter((row) =>
        itemArray.some(
            (item) =>
              //item.id !== row.id || // <-LINE IN QUESTION
                (item.id === row.id &&
                    Date.parse(row.updateDate + 'T' + row.updateTime) >
                        Date.parse(item.updateDate + 'T' + item.updateTime)),
        ),
    );

    console.log(filteredArray);

我不明白为什么这个|| 条件不能像我预期的那样工作?在上面的例子中,当 LINE IN QUESTION 被移除时,idDateArray 中的所有对象,其iditemArray 中的对象匹配并且日期/时间为&gt; itemArray 中的对象应被移除。他们是(剩下的就是 id 2)。

然后我添加 or 条件,然后我希望它不仅过滤匹配的 id 和大于日期时间的,还过滤那些没有任何匹配的 id。 IE。如果任一条件为真,请从idDateArray 中删除。

【问题讨论】:

  • 有问题的行被注释掉了
  • 我知道。如果取消注释,则不会运行任何条件。返回所有 5 个对象。

标签: javascript arrays typescript filter


【解决方案1】:

我的意思是,您是说“如果数组中有 any 项,item.id !== row.id 则保留它”,并且大概总是至少有一个 id 不存在的项'不匹配,你使用的是.some而不是.every

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多