【问题标题】:How to compare two different array and remove object from one Array based on Key?如何比较两个不同的数组并根据键从一个数组中删除对象?
【发布时间】:2020-10-16 17:40:42
【问题描述】:

我有两个数组对象,我想比较它们,如果两个数组中的值匹配则删除。

Arr1 = [
        {id: "one", name: "one", status: "Active"}, 
        {id: "two", name: "two", status: "Active"}, 
        {id: "three", name: "three", status: "Active"}
      ]

Arr2 = [
        {pid: "one", order: 1}, 
        {pid: "two", order: 2}
      ]

现在我想如果id === pid 那么它不应该返回。

finalArr = [
            {id: "three", name: "three", status: "Active"}
           ]

我尝试了以下解决方案,但不知何故它不起作用并返回空数组。

finalArr  = Arr1.filter((a) => {
    Arr2.some((b) => {
        a['id'] === b['pid'];        
    });
});

如果您需要更多信息,请告诉我。我希望我能够表达我的担忧。4

谢谢!

【问题讨论】:

  • some 应该返回一些东西。使用括号 ({) 会强制您添加 return,否则会隐式返回 void 0 (undefined)。

标签: javascript arrays typescript ecmascript-6 lodash


【解决方案1】:

您的方向几乎是正确的,您必须将! 条件放在some 之前,这样它就不会带来匹配的数组。这是一个班轮:

var Arr1 = [ {id: "one", name: "one", status: "Active"},  {id: "two", name: "two", status: "Active"},  {id: "three", name: "three", status: "Active"} ];

var Arr2 = [{pid: "one", order: 1},  {pid: "two", order: 2} ];

var result = Arr1.filter(k=>!Arr2.some(p=>p.pid==k.id));

console.log(result);

使用您的解决方案:

var Arr1 = [ {id: "one", name: "one", status: "Active"},  {id: "two", name: "two", status: "Active"},  {id: "three", name: "three", status: "Active"} ];

var Arr2 = [{pid: "one", order: 1},  {pid: "two", order: 2} ];

var finalArr = Arr1.filter((a) => {
    return !Arr2.some((b) => {
        return a['id'] === b['pid'];        
    });
});

console.log(finalArr);

【讨论】:

    【解决方案2】:

    既然你标记了,你可以考虑使用_.differenceWith() 方法,它允许你提供一个比较器函数来指定你应该通过什么属性来获取差异。但是,如果您还没有使用 lodash,那么最好使用普通方法。

    const arr1 = [{id: "one", name: "one", status: "Active"},  {id: "two", name: "two", status: "Active"}, {id: "three", name: "three", status: "Active"}];
    const arr2 = [{pid: "one", order: 1}, {pid: "two", order: 2}];
    const res = _.differenceWith(arr1, arr2, ({id}, {pid}) => id === pid);
    
    console.log(res); // [{ "id": "three", "name": "three", "status": "Active" }]
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

    【讨论】:

      【解决方案3】:
      const arr2Pid = Arr2.map((value) => value.pid); // getting the pid from array 2
      console.log(Arr1.filter((value) => arr2Pid.indexOf(value.id) < 0 )) // filtering the Arr1 if pid != id of Arr1
      

      【讨论】:

      • 如果您将arr2Pid 设为Set,您可以将其设为O(n+m) 而不是O(nm),因为您可以使用.has() 而不是.indexOf()
      • 正确,这是我们可以提高性能的地方。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 2012-12-06
      相关资源
      最近更新 更多