如何通过使用Javascript比较两组数组来获取唯一对象

时间:2015-11-04 09:46:50

标签: javascript arrays

我有以下两个数组:

var data1=[
    {
        "id": 1,
        "url": "http://192.168.1.165:90/asset/"
    },
    {
        "id": 2,
        "url": "Assigned"
    }


]
var data2=[
    {
        "id": 1,
        "url": "http://192.168.1.165:90/asset/"
    },
    {
        "id": 2,
        "url": "Assigned"
    },
{
        "id": 3,
        "url": "Assigned"
    }

]

结果:

var unique=[{ {
            "id": 3,
            "url": "Assigned"
        }}]

如何从这两个数组中获取唯一对象? 我尝试过这样的for循环:

var unique = [];
for(var i = 0; i < data2.length; i++){
    var found = false;
    for(var j = 0; data1.length; j++){
     if(data2[i].id == data1[j].id){
      found = true;
      break; 
    }
   }
   if(found == false){
   unique.push(array1[i]);
  }
}

但是希望使用功能性的javascript获得解决方案......

4 个答案:

答案 0 :(得分:1)

试试这个

var joined = data1.concat(data2);
var temp = [];
joined.forEach(function (x) {
    var objList=joined.filter(function(y){ return y.id == x.id});
    if(objList.length == 1) // if data count of current item in merged array is 1 that's means it belong to only one data source
        temp.push(x);
})

console.log(temp)

JSFIDDLE

答案 1 :(得分:1)

试试这个:首先获取data1中不在data2的对象,然后从data2移除{}} concat它与data2

<script>
var data1=[
       {
           "id": 1,
           "url": "http://192.168.1.165:90/asset/"
       },
       {
           "id": 2,
           "url": "Assigned"
       }


   ];
   var data2=[
       {
           "id": 1,
           "url": "http://192.168.1.165:90/asset/"
       },
       {
           "id": 2,
           "url": "Assigned"
       },
   {
           "id": 3,
           "url": "Assigned"
       }

   ];
   
   var arr3 = [];
   for(var i in data1){
      var dup = false;
      for (var j in data2){
    	  if (data2[j].id == data1[i].id && data2[j].url == data1[i].url) {
             data2.splice(j,1);
          }
      }
      if(dup) arr3.push(arr1[i])
      
   }

   arr3 = arr3.concat(data2);
console.log(arr3);
</script>

答案 2 :(得分:1)

编辑生成 唯一 对象

假设你有一个功能:

function unique(arr) {
var uni = [];
for(var i=0; i<arr.length; ++i) {
    var rep = -1;
    for(var j=0; j<arr.length; ++j)
        if(arr[i].id == arr[j].id) rep++;
    if (!rep) uni.push(arr[i]);
}
return uni;

}

这会起作用,并为您提供唯一的唯一对象:

var u = unique(data1.concat(data2));

答案 3 :(得分:1)

我们的想法是建立两个给定数组的并集,然后遍历String[] helper = {"upper section", "ones", "twos", "threes", "fours", "fives", "sixes", "total", "bonus", "total w bonus", "lower section", "3 of a kind", "4 of a kind", "full house", "small straight", "large straight", "YATHZEE", "chance", "total lower section", "total upper section", "grand total"}; for(int i = 0; i < rnc.length && i < helper.length; i++) { rnc[i][0] = helper[i]; } 并在setAsetA中查找匹配的属性和值。如果找到,则存储索引。如果有多个索引,请从union删除索引中的所有项目。

其余的是symmetric difference

union