比较2个对象数组并删除重复的javascript

时间:2017-08-08 08:04:59

标签: javascript arrays ecmascript-6

我试图将2个对象数组进行比较并删除重复项。例如......

var array1 = [0, 1, 2, 3, 4, 5, 6];
var array2 = [7, 8, 1, 2, 9, 10];

如何检查array2中是否有array1的任何元素,如果为true,则从array2中删除它以消除重复。

预期结果:array 2 = [7, 8, 9, 10]

感谢任何帮助,谢谢

3 个答案:

答案 0 :(得分:1)

只过滤第二个数组。

const array1 = [0, 1, 2, 3, 4, 5, 6];
const array2 = [7, 8, 1, 2, 9, 10];

const newArray = array2.filter(i => !array1.includes(i));

console.log(newArray);

答案 1 :(得分:1)

如果数组包含基本类型,则可以使用indexOfarray#reduce



const array1 = [0, 1, 2, 3, 4, 5, 6]
const array2 = [7, 8, 1, 2, 9, 10]

var result = array2.filter((num) => {
  return array1.indexOf(num) === -1;
});

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }




如果是对象,您可以在第二个数组中获取与第一个数据相比的唯一值,请使用array#reducearray#some



const person1 = [{"name":"a", "id":0},{"name":"A", "id":1},{"name":"B", "id":2},{"name":"C", "id":3},{"name":"D", "id":4},{"name":"E", "id":5},{"name":"F", "id":6}]
const person2 = [{"name":"G", "id":7},{"name":"H", "id":8},{"name":"A", "id":1},{"name":"B", "id":2},{"name":"I", "id":9}, {"name":"J", "id":10}]

var unique = person2.reduce((unique, o) => {
  let isFound = person1.some((b) => {
    return b.id === o.id;
  });
  if(!isFound)
    unique.push(o);
  return unique;
},[]);

console.log(unique);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 2 :(得分:1)

您可以使用:

messageWriter.WriteDocType("message", null, "work_request_20.dtd", null);

这应该能满足您的需求。或者另一种方式:

var array1 = [0, 1, 2, 3, 4, 5, 6];
var array2 = [7, 8, 1, 2, 9, 10];

/* run a filter function for every value in array2 and returned the final filtered array */
var array3 = array2.filter(function(currentValue, index, arr){
      return (array1.indexOf(currentValue) === -1); /* this will check whether currentValue exists in aray1 or not. */
});

console.log(array3) /* filtered array */

这应该适用于您的情况,除非有其他一些与之相关的外部因素。