比较两个数组并返回唯一值[重复]

时间:2022-04-12 12:03:16

This question already has an answer here:

这个问题在这里已有答案:

I have the two following arrays:

我有以下两个数组:

array1 = [{'itemCode':'a'}, {'itemCode':'b'}, {'itemCode':'c'}]; 
array2 = [{'itemCode':'a'}, {'itemCode':'b'}, {'itemCode':'d'}]; 

I'm looking for a way to slice array2 from array 1 and return the "F" value.

我正在寻找一种方法从数组1切片array2并返回“F”值。

Does anyone know of a quick way to do this in JavaScript, Im totally stumped.

有没有人知道在JavaScript中快速做到这一点,我完全难过。

I tried _difference and _unique from underscore, but that doesnt seem to be the right solution.

我从下划线尝试了_difference和_unique,但这似乎不是正确的解决方案。

var diffArray = _.difference(array1, array2);

Any help would be greatly appreciated!

任何帮助将不胜感激!

1 个解决方案

#1


Get the unique values from two arrays and put them in another array - Jquery I think this will answer your question

从两个数组中获取唯一值并将它们放在另一个数组中 - Jquery我认为这将回答您的问题

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

#1


Get the unique values from two arrays and put them in another array - Jquery I think this will answer your question

从两个数组中获取唯一值并将它们放在另一个数组中 - Jquery我认为这将回答您的问题

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