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

javascript - How to Subtract Multiple Objects from an Array with Another array - Stack Overflow

programmeradmin0浏览0评论

I'm trying to subtract, i.e. remove, multiple objects, namely the objects of array2 found in array1 so that the end result is that array2 only contains the "jean" object.

Help! I'm lost.

I tried multiple times code like the following example but it didn't worked.

array1= [{"caracname" : "charles"}, {"caracname" : "kevin"}]
array2= [{"caracname" : "charles"}, {"caracname" : "kevin"}, {"caracname" : "jean"}]
            
            array1.forEach(function (k) {
                delete array2[k];
            });
            
            console.log(array2);

I'm trying to subtract, i.e. remove, multiple objects, namely the objects of array2 found in array1 so that the end result is that array2 only contains the "jean" object.

Help! I'm lost.

I tried multiple times code like the following example but it didn't worked.

array1= [{"caracname" : "charles"}, {"caracname" : "kevin"}]
array2= [{"caracname" : "charles"}, {"caracname" : "kevin"}, {"caracname" : "jean"}]
            
            array1.forEach(function (k) {
                delete array2[k];
            });
            
            console.log(array2);

Share Improve this question edited Oct 15, 2017 at 20:59 slevy1 3,8202 gold badges29 silver badges33 bronze badges asked Oct 15, 2017 at 18:14 jeanjean 732 silver badges8 bronze badges 1
  • Possible duplicate of Compare two Javascript Arrays and remove Duplicates – John Ruddell Commented Oct 15, 2017 at 18:27
Add a ment  | 

4 Answers 4

Reset to default 3

A bit easier with a libraries like Lodash :

var array1 = [{"caracname" : "charles"}, {"caracname" : "kevin"}];
var array2 = [{"caracname" : "charles"}, {"caracname" : "kevin"}, {"caracname" : "jean"}];

var array3 = _.differenceWith(array2, array1, _.isEqual);

console.log( JSON.stringify(array3) );

// or 
_.pullAllWith(array2, array1, _.isEqual);

console.log( JSON.stringify(array2) );
<script src="https://cdnjs.cloudflare./ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


A bit less efficient alternative without library (might not work for objects with more than one property) :

var array1 = [{"caracname" : "charles"}, {"caracname" : "kevin"}];
var array2 = [{"caracname" : "charles"}, {"caracname" : "kevin"}, {"caracname" : "jean"}];

var j = JSON.stringify, array3 = array2.filter(e => array1.map(j).indexOf(j(e)) < 0);

console.log( j(array3) );

Here is how to do this:

function objectsEqual(o1, o2) {
    return o1.caracname === o2.caracname
}

function subtractArrays(a1, a2) {
    var arr = [];
    a1.forEach((o1) => {
       var found = false;
       a2.forEach((o2) => {
           if (objectsEqual(o1, o2)) {
                found = true;
           }  
       });
       if (!found) {
           arr.push(o1);
       }
    })
    return arr;
}

console.log(subtractArrays(array2, array1));

fixed in plunker: https://plnkr.co/edit/vA6oWg9R44f6k7ylyFh6?p=preview

As it turns out deleting an array element is not as easy as deleting a variable; see here. The "deleted" element is not deleted but acquires an undefined value while the length of the array stays the same.

Found some helpful advice here. So, you may use array2's splice method which according to MDN handily does the following:

The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

The following snippet works irrespective of the order of the elements in each array, as follows:

var arr1 = [{
  "caracname": "charles"
}, {
  "caracname": "kevin"
}];

var arr2 = [{
  "caracname": "charles"
}, {
  "caracname": "jean"
}, {
  "caracname": "kevin"
}];

var tmp1 = "",
    tmp2 = "";

for (var k = 0, key = "", maxLength = arr1.length; k < maxLength; k++) {
  key = Object.keys(arr1[k])[0];
  
  for (var j = 0, maxLength_2 = arr2.length; j < maxLength_2; j++) {
  
    tmp2 = arr2[j][key];
    tmp1 = arr1[k][key];
  
  if (tmp2 === tmp1) {
      arr2.splice(j, 1);
      maxLength_2--; // array2 length now one less
      break;
    }// end if
  }// end inner-for
}// end outer-for

console.log(arr2);

I've revised this example after running the code here, altering some variable names as a result.

As an aside, you should declare your arrays with var or optionally let; more info here and here.

Use this code: [ advised by @slevy1 ]

var array1= [{"caracname" : "charles"}, {"caracname" : "kevin"}]
var array2= [{"caracname" : "charles"}, {"caracname" : "kevin"}, {"caracname" : "jean"}]

array1.forEach(function (k) {
    var index = array1.valueOf(k);
    array2.splice(index, 1);
});

array2.forEach(function (o) {
    console.log(o.caracname);
});

codepen link

发布评论

评论列表(0)

  1. 暂无评论