简体   繁体   English

array.filter() 和 array.some() 没有按预期使用“||” (健康)状况

[英]array.filter() and array.some() not acting as expected with an '||' condition

Here is a working example (and here is a link to something you can play with):这是一个工作示例(是您可以玩的东西的链接):

  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);

What I am not understanding is why this ||我不明白的是为什么这|| condition won't work as I expect?条件不会像我预期的那样工作? In the above example, when the LINE IN QUESTION is removed, all objects in idDateArray whose id matches those in itemArray AND date/time is > those in itemArray should be removed.在上面的示例中,当删除 LINE IN QUESTION 时,idDateArray 中的所有对象,其ididDateArray中的对象匹配itemArray日期/时间> itemArray中的对象。 And they are (id 2 is all that is left).他们是(id 2 是剩下的)。

I then add in the or condition, which I would then expect to not only filter on matched id's and greater than date time, but also filter those that dont have any match on id.然后我添加 or 条件,然后我希望它不仅过滤匹配的 id 和大于日期时间,而且还过滤那些在 id 上没有任何匹配的。 IE If either condition is true, remove from idDateArray . IE 如果任一条件为真,则从idDateArray中删除。

I mean, you're saying "keep it if there is any item in the array where item.id.== row.id ", and there's presumably always going to be at least a single item where the id doesn't match, you're using .some not .every我的意思是,你是说“如果数组中有任何项目item.id.== row.id就保留它”,并且大概总是至少会有一个 ID 不匹配的项目,你用的是.some而不是.every

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM