通过比较新旧数组对象获取唯一值

时间:2019-09-11 12:31:47

标签: javascript jquery

比较两个对象数组以通过键 number

查找不同的值

假设旧对象由

组成
oldChoices = [{"number": 1, "text": "abc" }, {"number": 2, "text": "pqr" }]

新对象由

组成
newChoices = [{"number": 1, "text": "abc" }, {"number": 2, "text": "pqr" }, {"number": 3, "text": "xyz" }]

因此需要获得:

[{"number": 3, "text": "xyz" }]

注意:     1。在文本框的keypress事件中,值填充在newChoices数组中。     2. newChoices也可以在一开始就获得价值。

尝试1:

var uniqueTemp = [];
$.each(oldChoices, function(x, e1){
   $.each(newChoices, function(y, e2){
      if(e1.number != e2.number){
         uniqueTemp.push(e2);
      }
   });
})

尝试2:

var uniqueTemp = [];
oldChoices.filter(function(x){
   if(newChoices.indexOf(x.number) === -1){
    uniqueTemp.push(x);
    return true;
   }else{
    return false;
   }
});

预期:

[{"number": 3, "text": "xyz" }]

4 个答案:

答案 0 :(得分:2)

您的第二次尝试即将结束,只需更改为:

newChoices.filter((x) => {
   return (!oldChoices.find((choice) => choice.number === x.number));
});

答案 1 :(得分:2)

您可以使用Set并过滤新数组。

var oldChoices = [{ number: 1, text: "abc" }, { number: 2, text: "pqr" }],
    newChoices = [{ number: 1, text: "abc" }, { number: 2, text: "pqr" }, { number: 3, text: "xyz" }],
    old = new Set(oldChoices.map(({ number }) => number)),
    result = newChoices.filter(({ number }) => !old.has(number));

console.log(result);

答案 2 :(得分:1)

这是您的解决方案。只需使用flag就可以了。
arr中,您将有一个unique object符合预期。

var oldChoices = [{"number": 1, "text": "abc" }, {"number": 2, "text": "pqr" }]
var newChoices = [{"number": 1, "text": "abc" }, {"number": 2, "text": "pqr" }, {"number": 3, "text": "xyz" }];
var arr = []
var flag = 0;
newChoices.forEach(function(newChoice){
    oldChoices.forEach(function(oldChoice){
        if(oldChoice.number == newChoice.number){
            flag = 1;
        }
    });
    if(flag != 1){
        arr.push(newChoice);
    }
    flag = 0;
});

console.log(arr);

答案 3 :(得分:0)

这是一个通用函数,用于计算两个数组的差:

let arrayDifference = (v1, v2, cmp = null) => 
  [...v1.filter(o1 => !v2.some(o2 => cmp ? cmp(o1, o2) : o1 === o2)),  
   ...v2.filter(o1 => !v1.some(o2 => cmp ? cmp(o1, o2) : o1 === o2))]

比起您可以使用正确的比较功能调用它:

arrayDifference(
  oldChoices,
  newChoices,
  (o1, o2) => o1.number === o2.number
)

此函数查找在oldChoices和newChoices中都出现的唯一对象。

相关问题