最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Find difference between two arrays - Stack Overflow

programmeradmin5浏览0评论

I have following Plunkr which works perfectly.

It uses the _.differenceWith() function of lodash, in order two save all array values, which are not contained by the two arrays.

var result = _.differenceWith(data, test, _.isEqual);

Now I have two problems:

1.) In our project we use an older Lodash Version where the function differenceWith is not implemented

2.) I only need to pare one value of the array. This currently pares the plete objects. I only need to pare the id property.

I have following Plunkr which works perfectly.

https://plnkr.co/edit/WDjoEK7bAVpKSJbAmB9D?p=preview

It uses the _.differenceWith() function of lodash, in order two save all array values, which are not contained by the two arrays.

var result = _.differenceWith(data, test, _.isEqual);

Now I have two problems:

1.) In our project we use an older Lodash Version where the function differenceWith is not implemented

2.) I only need to pare one value of the array. This currently pares the plete objects. I only need to pare the id property.

Share Improve this question edited Jun 9, 2017 at 13:53 j08691 208k32 gold badges269 silver badges280 bronze badges asked Jun 9, 2017 at 13:51 user5417542user5417542 3,4068 gold badges31 silver badges55 bronze badges 3
  • _.filter(arr, x=>x.id="something") – dandavis Commented Jun 9, 2017 at 13:53
  • The Plunkr doesn't work perfectly. It says ReferenceError: _ is not defined. So what is your actual data? The data shown has no id property. – Jeremy Thille Commented Jun 9, 2017 at 14:10
  • Omg so so sorry, somehow there was an error. I updated it. Should work now :/ – user5417542 Commented Jun 9, 2017 at 14:23
Add a ment  | 

1 Answer 1

Reset to default 5

This will find the objects in arr1 that are not in arr2 based on the id attribute.

var arr1 = [ { "id": "1" }, { "id": "2" }, { "id": "3" } ];
var arr2 = [ { "id": "1" }, { "id": "2" } ];
var result = arr1.filter(o1 => arr2.filter(o2 => o2.id === o1.id).length === 0);
console.log(result);

Note that this example does not require lodash.

If you want to use a different parison instead of id, you can change the o2.id === o1.id part to a different property.

Here is a more generic solution:

var arr1 = [ { "name": "a" }, { "name": "b" }, { "name": "c" } ];
var arr2 = [ { "name": "a" }, { "name": "c" } ];
function differenceWith(a1, a2, prop) {
    return a1.filter(o1 => a2.filter(o2 => o2[prop] === o1[prop]).length === 0);
}
var result = differenceWith(arr1, arr2, 'name');
console.log(result);

发布评论

评论列表(0)

  1. 暂无评论