【问题标题】:Delete multiple elements by properties from array by list of properties按属性列表从数组中按属性删除多个元素
【发布时间】:2021-09-25 20:18:47
【问题描述】:

我有一个无法解决的问题,我觉得有点奇怪。有一个对象列表foo,每个对象都有一个userId 属性,我想过滤该列表以删除包含userId 的所有项目,这些项目位于bar 数组中。 我使用了filter()some() 方法,但是,它们仅在bar 数组只有一个元素时才有效。 some() 在找到第一个匹配元素时是否会以某种方式阻止整个过滤器运行? 如果您能向我解释为什么这不起作用,我将不胜感激。

示例代码:


let foo = [
  {
    "userId": 1,
  },
  {
    "userId": 2
  },
  {
    "userId": 3
  },
  {
    "userId": 4
  }
];

let bar = [1, 2];

console.log(foo.filter(user => bar.some(id => id !== user.userId)));

预期值:

[
  {
    "userId": 3
  },
  {
    "userId": 4
  }
]

但我得到了:

[
  {
    "userId": 1,
  },
  {
    "userId": 2
  },
  {
    "userId": 3
  },
  {
    "userId": 4
  }
]

【问题讨论】:

  • "some() 方法对数组中存在的每个元素执行一次callbackFn 函数直到找到callbackFn 返回真值的元素(转换为布尔值后变为真的值)。如果找到这样的元素,some()立即返回真。否则,some() 返回false。"
  • 使用.includes() 而不是.some()

标签: javascript arrays filtering


【解决方案1】:

您的条件当前检查是否条形数组中至少有一项与您正在迭代的 items 数组不同。对于所有项目都是如此。

您需要使用some() 检查存在的项目,并在此基础上返回反向值。

let foo = [
  {
    "userId": 1,
  },
  {
    "userId": 2
  },
  {
    "userId": 3
  },
  {
    "userId": 4
  }
];

let bar = [1, 2];

console.log(foo.filter(user => !bar.some(id => id === user.userId)));

【讨论】:

    【解决方案2】:

    您可以简单地使用includes 方法来检查这种情况。

    let foo = [
      {
        "userId": 1,
      },
      {
        "userId": 2
      },
      {
        "userId": 3
      },
      {
        "userId": 4
      }
    ];
    
    let bar = [1, 2];
    // filter out for user IDs not in bar
    console.log(foo.filter(user => !bar.includes(user.userId)));

    有关包含方法的更多信息:MDN

    【讨论】:

      【解决方案3】:

      some() 方法测试数组中是否至少有一个元素通过了测试。

      解释为什么 some() 在这里不起作用:

      [1,2].some(id !== 1) 将返回 true 因为 id 2 !== 1

      [1,2].some(id !== 2) 将返回 true 因为 id 1 !== 2

      [1,2].some(id !== 3) 将返回 true 因为 id 1 !== 3

      [1,2].some(id !== 4) 将返回 true 因为 id 1 !== 4

      【讨论】:

        猜你喜欢
        • 2018-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-10
        • 1970-01-01
        • 1970-01-01
        • 2021-11-25
        相关资源
        最近更新 更多