【问题标题】:Javascript : Check array element contains element from another arrayJavascript:检查数组元素是否包含来自另一个数组的元素
【发布时间】:2022-01-02 12:30:57
【问题描述】:

我有下面的数组-

Array(12)
[
{username:"abc" , userpid:"M123"},
{username:"xyz" , userpid:"T234"},
{username:"mnp" , userpid:"L678"}
.
.
]

我有另一个数组 -

Array (6)
    [
    {projectname:"corporate" , projecttype:"oil" userpid:"M123"},
    {projectname:"corporate" , projecttype:"oil" userpid:"K123"},
    {projectname:"corporate" , projecttype:"oil" userpid:"P123"},
    .
    .
    ]

在这里,我想从第一个数组中过滤掉所有 userpid 不在第二个数组中的元素。例如。 userpid M123 存在于第二个数组中,这就是输出的原因 -

[
{username:"xyz" , userpid:"T234"},
{username:"mnp" , userpid:"L678"}
]

I tried with - 

array1.some(x=>x.userpid!=(array2.filter(y=>y.userpid)))

但这会导致语法错误。

【问题讨论】:

  • 您将字符串 (x.userpid) 与数组(.filter() 的返回值)进行比较
  • 试试,array1.filter(el => array2.every(f => f.userpid !== el.userpid));

标签: javascript jquery arrays reactjs


【解决方案1】:

类似的东西

const arr1 = [
{username:"abc" , userpid:"M123"},
{username:"xyz" , userpid:"T234"},
{username:"mnp" , userpid:"L678"}];

const arr2 = [
    {projectname:"corporate", projecttype:"oil", userpid:"M123"},
    {projectname:"corporate", projecttype:"oil", userpid:"K123"},
    {projectname:"corporate", projecttype:"oil", userpid:"P123"},];

const result = arr1.filter(item => !arr2.some(v => item.userpid === v.userpid));

console.log(result);

【讨论】:

    猜你喜欢
    • 2021-01-30
    • 2023-03-08
    • 2019-05-05
    • 2020-11-21
    • 2017-03-03
    相关资源
    最近更新 更多