How to get the difference between two arrays of objects in JavaScript

前端 未结 18 1365
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 04:45

I have two result sets like this:

// Result 1
[
    { value: \"0\", display: \"Jamsheer\" },
    { value: \"1\", display: \"Muhammed\" },
    { value: \"2\",         


        
18条回答
  •  梦如初夏
    2020-11-22 04:58

    You could use Array.prototype.filter() in combination with Array.prototype.some().

    Here is an example (assuming your arrays are stored in the variables result1 and result2):

    //Find values that are in result1 but not in result2
    var uniqueResultOne = result1.filter(function(obj) {
        return !result2.some(function(obj2) {
            return obj.value == obj2.value;
        });
    });
    
    //Find values that are in result2 but not in result1
    var uniqueResultTwo = result2.filter(function(obj) {
        return !result1.some(function(obj2) {
            return obj.value == obj2.value;
        });
    });
    
    //Combine the two arrays of unique entries
    var result = uniqueResultOne.concat(uniqueResultTwo);
    

提交回复
热议问题