【问题标题】:Get result of array elements which are not matched into a single array获取未匹配到单个数组中的数组元素的结果
【发布时间】:2019-10-14 17:24:48
【问题描述】:

我是 Javascript 新手。我有以下 Mongodb 结果数组

Result = [
          {
            "userId": "5cecfab4219aca350421b063",
            "providers": [
              "1689736266",
              "1598763690",
              "1528069614",
              "1831364272",
              "1548463045",
              "1245301159",
              "1386616399",
              "1790775971",
              "1629462130",
              "1992169783"
            ],
            "countByType": {
              "doctors": 6,
              "labs": 0,
              "hospitals": 0,
              "imagingCenters": 0,
              "other": 4
            },
            "id": "5cecfab4219aca350421b066"
          }
         ]

我有另一个数组

newArray = [1689736266, 1831364272, 123456789, 235695654 ];

如何获取newArray中不在MongoDBResult providers数组中的数组值。

例如:anotherArray = [123456789, 235695654];

另外,如何使用 Javascript 获取提供者数组结果。

【问题讨论】:

  • 可以使用数组差异,参考stackoverflow.com/questions/1187518/…
  • Result.providers.filter(provider => !newArray.includes(provider))
  • @nickzoum 你必须在 newArray 而不是提供者上应用过滤器,但这就是想法

标签: javascript arrays loops iteration javascript-objects


【解决方案1】:

您可以在newArray 上使用filter(),并使用includes() 检查它是否存在于Result 的提供者数组中

const Result = [ { "userId": "5cecfab4219aca350421b063", "providers": [ "1689736266", "1598763690", "1528069614", "1831364272", "1548463045", "1245301159", "1386616399", "1790775971", "1629462130", "1992169783" ], "countByType": { "doctors": 6, "labs": 0, "hospitals": 0, "imagingCenters": 0, "other": 4 }, "id": "5cecfab4219aca350421b066" } ]
         
const newArray = [1689736266, 1831364272, 123456789, 235695654 ];
const anotherArray = newArray.filter(x => !Result[0].providers.includes(String(x)))

console.log(anotherArray)

【讨论】:

  • 还有如何检查 anotherArray 在 if 条件下是否有一些值,只有 if,然后执行这个块。
  • @Vishnu if(anotherArray.includes(some value)){...}
  • 现在我有一个空数组。因此,如果数组为空,请不要执行代码。怎么达到这个兄弟?
  • @Vishnu 请更新您的问题并详细说明。
【解决方案2】:

使用filter():

 

const providers =  [
          "1689736266",
          "1598763690",
          "1528069614",
          "1831364272",
          "1548463045",
          "1245301159",
          "1386616399",
          "1790775971",
          "1629462130",
          "1992169783"
        ];

const newArray = [1689736266, 1831364272, 123456789, 235695654 ];

const res = providers.filter(e => !newArray.includes("" + e));
console.log(res);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    相关资源
    最近更新 更多