我对如何比较两个数组对象感到困惑。特殊值将忽略的值作为数组得到。
var Arr1 = [
{
jobId:"j1"
},
{
jobId:"j2"
},
{
jobId:"j3"
},
{
jobId:"j4"
},
]
var Arr2 = [
{
jobId:"j1"
},
{
jobId:"j2"
},
]
我想要我的结果......
//neglected values
[
{
jobId:"j3"
},
{
jobId:"j4"
},
]
答案 0 :(得分:3)
答案 1 :(得分:2)
过滤(Array#filter
)将第一个数组的元素向下移动到第二个数组中没有(!
)一些(Array#some
)匹配作业ID的元素。
Arr1.filter(arr1Elt => !Arr2.some(arr2Elt => arr2Elt.jobId === arr1Elt.jobId))
使用逐行评论样式:
Arr1 // From Arr1,
.filter( // keep
arr1Elt => // elements for which
! // it is not the case that
Arr2 // Arr2 has
.some( // some
arr2Elt => // elements for which
arr2Elt.jobId // the job ID
=== // is equal to
arr1Elt.jobId // the job ID from the first array.
)
)
答案 2 :(得分:2)
您可以使用lodash的_.differenceBy()
查找Arr1
中遗失的Arr2
项。
var Arr1 = [{"jobId":"j1"},{"jobId":"j2"},{"jobId":"j3"},{"jobId":"j4"}];
var Arr2 = [{"jobId":"j1"},{"jobId":"j2"}];
// find items that are in Arr1, but not in Arr2, compare items by their jobId
var result = _.differenceBy(Arr1, Arr2 , 'jobId');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.3/lodash.min.js"></script>
答案 3 :(得分:1)
您可以在 Arr1 上使用Array.prototype.filter
,并使用Array.prototype.some
检查其任何条目是否在 Arr2 中 - 请参阅下面的演示:
var Arr1=[{jobId:"j1"},{jobId:"j2"},{jobId:"j3"},{jobId:"j4"}];
var Arr2=[{jobId:"j1"},{jobId:"j2"}];
var result = Arr1.filter(function(e){
return !Arr2.some(function(k){
return k.jobId === e.jobId;
});
});
console.log(result);