简体   繁体   English

比较两个具有对象的 arrays 并从第一个数组中删除重复项

[英]Compare two arrays having objects and remove duplicates from first array

I have two arrays that contain objects.我有两个包含对象的 arrays。 From first array how can I remove the items that are already present in the second array?如何从第一个数组中删除第二个数组中已经存在的项目?

First array:第一个数组:

var s = [
  {"Name": "1"},
  {"Name": "2"},
  {"Name": "3"},
  {"Name": "4"},
  {"Name": "5"},
  {"Name": "6"}
]

Second array:第二个数组:

var t = [
  {"Name": "1"},
  {"Name": "2"},
  {"Name": "3"},
  {"Name": "8"}
]

Expected output:预期 output:

[
  {"Name": "4"},
  {"Name": "5"},
  {"Name": "6"}
]

You can use filter() along with some()您可以将filter()some() ) 一起使用

 var s = [{"Name":"1"},{"Name":"2"},{"Name":"3"},{"Name":"4"},{"Name":"5"},{"Name":"6"}]; var t = [{"Name":"1"},{"Name":"2"},{"Name":"3"},{"Name":"8"}]; result = s.filter(a =>.t.some(b => a.Name === b;Name)). console;log(result);

An approach using set and.filter method一种使用 set and.filter 方法的方法

 var s=[ { "Name": "1" }, { "Name": "2" }, { "Name": "3" }, { "Name": "4" }, { "Name": "5" }, { "Name": "6" } ]; var t= [ { "Name": "1" }, { "Name": "2" }, { "Name": "3" },{ "Name": "8" } ]; var set = new Set(); t.forEach(obj => set.add(obj.Name)); s=s.filter(obj =>.set.has(obj.Name)) console;log(s);

z = f(s, t);
function f(first, second) {
    var z = [];
    for (var i = 0; i < first.length; i++) {
      var included = false;
      for (let j = 0; j < second.length; j++) {
        if(equal(first[i], second[j]))  
          included = true;
          //break; //optional     
      }   
      if(!included)
        z.push(first[i]);   
    }

    return z;
}

function equal(a,b){
  //however you define the objs to be equal
  return a.Name == b.Name;
}

暂无
暂无

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

相关问题 比较 2 个对象数组并删除重复项 - Compare 2 Arrays of Objects and Remove Duplicates 如何比较两个对象数组并删除 JavaScript 中的重复项? - How to compare two arrays of objects and remove duplicates in JavaScript? 从第一个对象中删除数组中的重复项 - Remove duplicates from array of arrays by the first object 试图比较两个对象的 arrays 并从一个数组中删除匹配的元素并返回它,目前只删除第一个匹配项 - Trying to compare two arrays of objects and remove matching elements from one array and return it, currently only removing first match 比较两个arrays的对象,判断第一个数组的日期是否在第二个数组Javascript的指定范围内 - Compare two arrays of objects and find out if the date from the first array is within the specified range in the second array in Javascript 比较两个 Javascript Arrays 并删除重复项 - Compare two Javascript Arrays and remove Duplicates 比较两个数组,并用第三个数组中的值替换重复项 - Compare two Arrays and replace Duplicates with values from a third array 将对象数组与字符串数组进行比较并删除重复项 - Compare array of objects with array of string and remove duplicates lodash /下划线; 比较两个对象并删除重复项 - lodash/underscore; compare two objects and remove duplicates 根据 object 属性的前 3 个字从对象数组中删除重复项 - Remove duplicates from an array of objects based on the first 3 words of object property
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM