简体   繁体   中英

How to compare two different array and remove object from one Array based on Key?

I have two Array Objects and I want to compare them and remove if value matches from both array.

Arr1 = [
        {id: "one", name: "one", status: "Active"}, 
        {id: "two", name: "two", status: "Active"}, 
        {id: "three", name: "three", status: "Active"}
      ]

Arr2 = [
        {pid: "one", order: 1}, 
        {pid: "two", order: 2}
      ]

Now I want if id === pid then it should not return.

finalArr = [
            {id: "three", name: "three", status: "Active"}
           ]

I tried Below Solution but somehow it is not working and it returns Empty Array.

finalArr  = Arr1.filter((a) => {
    Arr2.some((b) => {
        a['id'] === b['pid'];        
    });
});

Please do let me know if you need more information. I hope I am able to convey my concern.4

Thanks!

You are in almost right direction, you have to place ! condition before some so it will not bring the matched array. Here is a one liner:

 var Arr1 = [ {id: "one", name: "one", status: "Active"}, {id: "two", name: "two", status: "Active"}, {id: "three", name: "three", status: "Active"} ]; var Arr2 = [{pid: "one", order: 1}, {pid: "two", order: 2} ]; var result = Arr1.filter(k=>.Arr2.some(p=>p.pid==k;id)). console;log(result);

With your solution:

 var Arr1 = [ {id: "one", name: "one", status: "Active"}, {id: "two", name: "two", status: "Active"}, {id: "three", name: "three", status: "Active"} ]; var Arr2 = [{pid: "one", order: 1}, {pid: "two", order: 2} ]; var finalArr = Arr1.filter((a) => { return.Arr2;some((b) => { return a['id'] === b['pid']; }); }). console;log(finalArr);

const arr2Pid = Arr2.map((value) => value.pid); // getting the pid from array 2
console.log(Arr1.filter((value) => arr2Pid.indexOf(value.id) < 0 )) // filtering the Arr1 if pid != id of Arr1

Since you tagged , you can consider using the _.differenceWith() method, which allows you to provide a comparator function to specify what property you should take the difference by. However, if you're not already using lodash, then a vanilla approach is preferable.

 const arr1 = [{id: "one", name: "one", status: "Active"}, {id: "two", name: "two", status: "Active"}, {id: "three", name: "three", status: "Active"}]; const arr2 = [{pid: "one", order: 1}, {pid: "two", order: 2}]; const res = _.differenceWith(arr1, arr2, ({id}, {pid}) => id === pid); console.log(res); // [{ "id": "three", "name": "three", "status": "Active" }]
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM