如何在JavaScript中获取两个对象数组之间的差异

时间:2021-10-12 21:29:49

I have two result sets like this:

我有两个这样的结果集:

// Result 1
[
    { value="4a55eff3-1e0d-4a81-9105-3ddd7521d642", display="Jamsheer" },
    { value="644838b3-604d-4899-8b78-09e4799f586f", display="Muhammed" },
    { value="b6ee537a-375c-45bd-b9d4-4dd84a75041d", display="Ravi" },
    { value="e97339e1-939d-47ab-974c-1b68c9cfb536", display="Ajmal" },
    { value="a63a6f77-c637-454e-abf2-dfb9b543af6c", display="Ryan" }
]

// Result 2
[
    { value="4a55eff3-1e0d-4a81-9105-3ddd7521d642", display="Jamsheer", $$hashKey="008" },
    { value="644838b3-604d-4899-8b78-09e4799f586f", display="Muhammed", $$hashKey="009" },
    { value="b6ee537a-375c-45bd-b9d4-4dd84a75041d", display="Ravi", $$hashKey="00A" },
    { value="e97339e1-939d-47ab-974c-1b68c9cfb536", display="Ajmal", $$hashKey="00B" }
]

The final result I need is the difference between these arrays – the final result should be like this:

我需要的最终结果是这些数组之间的区别 - 最终结果应该是这样的:

[{ value="a63a6f77-c637-454e-abf2-dfb9b543af6c", display="Ryan" }]

Is it possible to do something like this in JavaScript?

是否可以在JavaScript中执行此类操作?

8 个解决方案

#1


71  

Using only native JS, something like this will work:

仅使用本机JS,这样的东西将起作用:

a = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal"},  { value:"a63a6f77-c637-454e-abf2-dfb9b543af6c", display:"Ryan"}]
b = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer", $$hashKey:"008"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed", $$hashKey:"009"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi", $$hashKey:"00A"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal", $$hashKey:"00B"}]

function comparer(otherArray){
  return function(current){
    return otherArray.filter(function(other){
      return other.value == current.value && other.display == current.display
    }).length == 0;
  }
}

var onlyInA = a.filter(comparer(b));
var onlyInB = b.filter(comparer(a));

result = onlyInA.concat(onlyInB);

console.log(result);

#2


26  

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

您可以将Array.prototype.filter()与Array.prototype.some()结合使用。

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

下面是一个示例(假设您的数组存储在变量result1和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);

#3


12  

I take a slightly more general-purpose approach, although similar in ideas to the approaches of both @Cerbrus and @Kasper Moerch. I create a function that accepts a predicate to determine if two objects are equal (here we ignore the $$hashKey property, but it could be anything) and return a function which calculates the symmetric difference of two lists based on that predicate:

我采取了一种更为通用的方法,尽管与@Cerbrus和@Kasper Moerch的方法相似。我创建了一个接受谓词的函数来确定两个对象是否相等(这里我们忽略$$ hashKey属性,但它可以是任何东西)并返回一个函数,该函数根据该谓词计算两个列表的对称差异:

a = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal"},  { value:"a63a6f77-c637-454e-abf2-dfb9b543af6c", display:"Ryan"}]
b = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer", $$hashKey:"008"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed", $$hashKey:"009"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi", $$hashKey:"00A"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal", $$hashKey:"00B"}]

var makeSymmDiffFunc = (function() {
    var contains = function(pred, a, list) {
        var idx = -1, len = list.length;
        while (++idx < len) {if (pred(a, list[idx])) {return true;}}
        return false;
    };
    var complement = function(pred, a, b) {
        return a.filter(function(elem) {return !contains(pred, elem, b);});
    };
    return function(pred) {
        return function(a, b) {
            return complement(pred, a, b).concat(complement(pred, b, a));
        };
    };
}());

var myDiff = makeSymmDiffFunc(function(x, y) {
    return x.value === y.value && x.display === y.display;
});

var result = myDiff(a, b); //=>  {value="a63a6f77-c637-454e-abf2-dfb9b543af6c", display="Ryan"}

It has one minor advantage over Cerebrus's approach (as does Kasper Moerch's approach) in that it escapes early; if it finds a match, it doesn't bother checking the rest of the list. If I had a curry function handy, I would do this a little differently, but this works fine.

与Cerebrus的方法相比,它有一个小优势(Kasper Moerch的方法也是如此),因为它很早就逃脱了;如果找到匹配,则不会检查列表的其余部分。如果我有一个方便的咖喱功能,我会这样做有点不同,但这很好。

Explanation

A comment asked for a more detailed explanation for beginners. Here's an attempt.

评论要求为初学者提供更详细的解释。这是一次尝试。

We pass the following function to makeSymmDiffFunc:

我们将以下函数传递给makeSymmDiffFunc:

function(x, y) {
    return x.value === y.value && x.display === y.display;
}

This function is how we decide that two objects are equal. Like all functions that return true or false, it can be called a "predicate function", but that's just terminology. The main point is that makeSymmDiffFunc is configured with a function that accepts two objects and returns true if we consider them equal, false if we don't.

这个函数就是我们决定两个对象是否相等的方法。像所有返回true或false的函数一样,它可以被称为“谓词函数”,但这只是术语。重点是makeSymmDiffFunc配置了一个接受两个对象的函数,如果我们认为它们相等则返回true,否则返回false。

Using that, makeSymmDiffFunc (read "make symmetric difference function") returns us a new function:

使用它,makeSymmDiffFunc(读取“make symmetric difference function”)返回一个新函数:

        return function(a, b) {
            return complement(pred, a, b).concat(complement(pred, b, a));
        };

This is the function we will actually use. We pass it two lists and it finds the elements in the first not in the second, then those in the second not in the first and combine these two lists.

这是我们实际使用的功能。我们传递两个列表,它找到第一个不在第二个中的元素,然后在第二个中不在第一个中的元素,并组合这两个列表。

Looking over it again, though, I could definitely have taken a cue from your code and simplified the main function quite a bit by using some:

但是,再看一遍,我肯定可以从你的代码中获得一些提示并通过使用一些简化主要功能:

var makeSymmDiffFunc = (function() {
    var complement = function(pred, a, b) {
        return a.filter(function(x) {
            return !b.some(function(y) {return pred(x, y);});
        });
    };
    return function(pred) {
        return function(a, b) {
            return complement(pred, a, b).concat(complement(pred, b, a));
        };
    };
}());

complement uses the predicate and returns the elements of its first list not in its second. This is simpler than my first pass with a separate contains function.

complement使用谓词并返回其第一个列表的元素而不是第二个列表。这比我第一次使用单独的contains函数简单。

Finally, the main function is wrapped in an immediately invoked function expression (IIFE) to keep the internal complement function out of the global scope.

最后,main函数包含在一个立即调用的函数表达式(IIFE)中,以保持内部补充函数不在全局范围内。


Update, a few years later

几年后更新

Now that ES2015 has become pretty well ubiquitous, I would suggest the same technique, with a lot less boilerplate:

既然ES2015已经变得无处不在,我建议使用相同的技术,并且更少的样板:

const diffBy = (pred) => (a, b) => a.filter(x => !b.some(y => pred(x, y)))
const makeSymmDiffFunc = (pred) => (a, b) => diffBy(pred)(a, b).concat(diffBy(pred)(b, a))

const myDiff = makeSymmDiffFunc((x, y) => x.value === y.value && x.display === y.display)

const result = myDiff(a, b)
//=>  {value="a63a6f77-c637-454e-abf2-dfb9b543af6c", display="Ryan"}

#4


2  

I think the @Cerbrus solution is spot on. I have implemented the same solution but extracted the repeated code into it's own function (DRY).

我认为@Cerbrus解决方案很有用。我已经实现了相同的解决方案,但将重复的代码提取到它自己的函数(DRY)中。

 function filterByDifference(array1, array2, compareField) {
  var onlyInA = differenceInFirstArray(array1, array2, compareField);
  var onlyInb = differenceInFirstArray(array2, array1, compareField);
  return onlyInA.concat(onlyInb);
}

function differenceInFirstArray(array1, array2, compareField) {
  return array1.filter(function (current) {
    return array2.filter(function (current_b) {
        return current_b[compareField] === current[compareField];
      }).length == 0;
  });
}

#5


1  

import differenceBy from 'lodash/differenceBy'

const myDifferences = differenceBy(Result1, Result2, 'value')

This will return the difference between two arrays of objects, using the key value to compare them. Note two things with the same value will not be returned, as the other keys are ignored.

这将返回两个对象数组之间的差异,使用键值来比较它们。请注意,不会返回具有相同值的两个内容,因为忽略其他键。

This is a part of lodash.

这是lodash的一部分。

#6


0  

I've made a generalized diff that compare 2 objects of any kind and can run a modification handler gist.github.com/bortunac "diff.js" an ex of using :

我已经制作了一个广义差异,可以比较任何类型的2个对象,并且可以运行修改处理程序gist.github.com/bortunac“diff.js”,使用前者:

old_obj={a:1,b:2,c:[1,2]}
now_obj={a:2 , c:[1,3,5],d:55}

so property a is modified, b is deleted, c modified, d is added

所以属性a被修改,b被删除,c被修改,d被添加

var handler=function(type,pointer){
console.log(type,pointer,this.old.point(pointer)," | ",this.now.point(pointer)); 

}

}

now use like

现在使用像

df=new diff();
df.analize(now_obj,old_obj);
df.react(handler);

the console will show

控制台将显示

mdf ["a"]  1 | 2 
mdf ["c", "1"]  2 | 3 
add ["c", "2"]  undefined | 5 
add ["d"]  undefined | 55 
del ["b"]  2 | undefined 

#7


0  

You can create an object with keys as the unique value corresponding for each object in array and then filter each array based on existence of the key in other's object. It reduces the complexity of the operation.

您可以使用键创建一个对象作为对应于数组中每个对象的唯一值,然后根据其他对象中键的存在过滤每个数组。它降低了操作的复杂性。

ES6

ES6

let a = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal"},  { value:"a63a6f77-c637-454e-abf2-dfb9b543af6c", display:"Ryan"}];
let b = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer", $$hashKey:"008"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed", $$hashKey:"009"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi", $$hashKey:"00A"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal", $$hashKey:"00B"}];

let valuesA = a.reduce((a,{value}) => Object.assign(a, {[value]:value}), {});
let valuesB = b.reduce((a,{value}) => Object.assign(a, {[value]:value}), {});
let result = [...a.filter(({value}) => !valuesB[value]), ...b.filter(({value}) => !valuesA[value])];
console.log(result);

ES5

ES5

var a = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal"},  { value:"a63a6f77-c637-454e-abf2-dfb9b543af6c", display:"Ryan"}];
var b = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer", $$hashKey:"008"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed", $$hashKey:"009"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi", $$hashKey:"00A"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal", $$hashKey:"00B"}];

var valuesA = a.reduce(function(a,c){a[c.value] = c.value; return a; }, {});
var valuesB = b.reduce(function(a,c){a[c.value] = c.value; return a; }, {});
var result = a.filter(function(c){ return !valuesB[c.value]}).concat(b.filter(function(c){ return !valuesA[c.value]}));
console.log(result);

#8


-4  

If you are willing to use external libraries, You can use _.difference in underscore.js to achieve this. _.difference returns the values from array that are not present in the other arrays.

如果您愿意使用外部库,可以在underscore.js中使用_.difference来实现此目的。 _.difference返回数组中其他数组中不存在的值。

_.difference([1,2,3,4,5][1,4,10])

==>[2,3,5]

#1


71  

Using only native JS, something like this will work:

仅使用本机JS,这样的东西将起作用:

a = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal"},  { value:"a63a6f77-c637-454e-abf2-dfb9b543af6c", display:"Ryan"}]
b = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer", $$hashKey:"008"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed", $$hashKey:"009"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi", $$hashKey:"00A"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal", $$hashKey:"00B"}]

function comparer(otherArray){
  return function(current){
    return otherArray.filter(function(other){
      return other.value == current.value && other.display == current.display
    }).length == 0;
  }
}

var onlyInA = a.filter(comparer(b));
var onlyInB = b.filter(comparer(a));

result = onlyInA.concat(onlyInB);

console.log(result);

#2


26  

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

您可以将Array.prototype.filter()与Array.prototype.some()结合使用。

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

下面是一个示例(假设您的数组存储在变量result1和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);

#3


12  

I take a slightly more general-purpose approach, although similar in ideas to the approaches of both @Cerbrus and @Kasper Moerch. I create a function that accepts a predicate to determine if two objects are equal (here we ignore the $$hashKey property, but it could be anything) and return a function which calculates the symmetric difference of two lists based on that predicate:

我采取了一种更为通用的方法,尽管与@Cerbrus和@Kasper Moerch的方法相似。我创建了一个接受谓词的函数来确定两个对象是否相等(这里我们忽略$$ hashKey属性,但它可以是任何东西)并返回一个函数,该函数根据该谓词计算两个列表的对称差异:

a = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal"},  { value:"a63a6f77-c637-454e-abf2-dfb9b543af6c", display:"Ryan"}]
b = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer", $$hashKey:"008"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed", $$hashKey:"009"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi", $$hashKey:"00A"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal", $$hashKey:"00B"}]

var makeSymmDiffFunc = (function() {
    var contains = function(pred, a, list) {
        var idx = -1, len = list.length;
        while (++idx < len) {if (pred(a, list[idx])) {return true;}}
        return false;
    };
    var complement = function(pred, a, b) {
        return a.filter(function(elem) {return !contains(pred, elem, b);});
    };
    return function(pred) {
        return function(a, b) {
            return complement(pred, a, b).concat(complement(pred, b, a));
        };
    };
}());

var myDiff = makeSymmDiffFunc(function(x, y) {
    return x.value === y.value && x.display === y.display;
});

var result = myDiff(a, b); //=>  {value="a63a6f77-c637-454e-abf2-dfb9b543af6c", display="Ryan"}

It has one minor advantage over Cerebrus's approach (as does Kasper Moerch's approach) in that it escapes early; if it finds a match, it doesn't bother checking the rest of the list. If I had a curry function handy, I would do this a little differently, but this works fine.

与Cerebrus的方法相比,它有一个小优势(Kasper Moerch的方法也是如此),因为它很早就逃脱了;如果找到匹配,则不会检查列表的其余部分。如果我有一个方便的咖喱功能,我会这样做有点不同,但这很好。

Explanation

A comment asked for a more detailed explanation for beginners. Here's an attempt.

评论要求为初学者提供更详细的解释。这是一次尝试。

We pass the following function to makeSymmDiffFunc:

我们将以下函数传递给makeSymmDiffFunc:

function(x, y) {
    return x.value === y.value && x.display === y.display;
}

This function is how we decide that two objects are equal. Like all functions that return true or false, it can be called a "predicate function", but that's just terminology. The main point is that makeSymmDiffFunc is configured with a function that accepts two objects and returns true if we consider them equal, false if we don't.

这个函数就是我们决定两个对象是否相等的方法。像所有返回true或false的函数一样,它可以被称为“谓词函数”,但这只是术语。重点是makeSymmDiffFunc配置了一个接受两个对象的函数,如果我们认为它们相等则返回true,否则返回false。

Using that, makeSymmDiffFunc (read "make symmetric difference function") returns us a new function:

使用它,makeSymmDiffFunc(读取“make symmetric difference function”)返回一个新函数:

        return function(a, b) {
            return complement(pred, a, b).concat(complement(pred, b, a));
        };

This is the function we will actually use. We pass it two lists and it finds the elements in the first not in the second, then those in the second not in the first and combine these two lists.

这是我们实际使用的功能。我们传递两个列表,它找到第一个不在第二个中的元素,然后在第二个中不在第一个中的元素,并组合这两个列表。

Looking over it again, though, I could definitely have taken a cue from your code and simplified the main function quite a bit by using some:

但是,再看一遍,我肯定可以从你的代码中获得一些提示并通过使用一些简化主要功能:

var makeSymmDiffFunc = (function() {
    var complement = function(pred, a, b) {
        return a.filter(function(x) {
            return !b.some(function(y) {return pred(x, y);});
        });
    };
    return function(pred) {
        return function(a, b) {
            return complement(pred, a, b).concat(complement(pred, b, a));
        };
    };
}());

complement uses the predicate and returns the elements of its first list not in its second. This is simpler than my first pass with a separate contains function.

complement使用谓词并返回其第一个列表的元素而不是第二个列表。这比我第一次使用单独的contains函数简单。

Finally, the main function is wrapped in an immediately invoked function expression (IIFE) to keep the internal complement function out of the global scope.

最后,main函数包含在一个立即调用的函数表达式(IIFE)中,以保持内部补充函数不在全局范围内。


Update, a few years later

几年后更新

Now that ES2015 has become pretty well ubiquitous, I would suggest the same technique, with a lot less boilerplate:

既然ES2015已经变得无处不在,我建议使用相同的技术,并且更少的样板:

const diffBy = (pred) => (a, b) => a.filter(x => !b.some(y => pred(x, y)))
const makeSymmDiffFunc = (pred) => (a, b) => diffBy(pred)(a, b).concat(diffBy(pred)(b, a))

const myDiff = makeSymmDiffFunc((x, y) => x.value === y.value && x.display === y.display)

const result = myDiff(a, b)
//=>  {value="a63a6f77-c637-454e-abf2-dfb9b543af6c", display="Ryan"}

#4


2  

I think the @Cerbrus solution is spot on. I have implemented the same solution but extracted the repeated code into it's own function (DRY).

我认为@Cerbrus解决方案很有用。我已经实现了相同的解决方案,但将重复的代码提取到它自己的函数(DRY)中。

 function filterByDifference(array1, array2, compareField) {
  var onlyInA = differenceInFirstArray(array1, array2, compareField);
  var onlyInb = differenceInFirstArray(array2, array1, compareField);
  return onlyInA.concat(onlyInb);
}

function differenceInFirstArray(array1, array2, compareField) {
  return array1.filter(function (current) {
    return array2.filter(function (current_b) {
        return current_b[compareField] === current[compareField];
      }).length == 0;
  });
}

#5


1  

import differenceBy from 'lodash/differenceBy'

const myDifferences = differenceBy(Result1, Result2, 'value')

This will return the difference between two arrays of objects, using the key value to compare them. Note two things with the same value will not be returned, as the other keys are ignored.

这将返回两个对象数组之间的差异,使用键值来比较它们。请注意,不会返回具有相同值的两个内容,因为忽略其他键。

This is a part of lodash.

这是lodash的一部分。

#6


0  

I've made a generalized diff that compare 2 objects of any kind and can run a modification handler gist.github.com/bortunac "diff.js" an ex of using :

我已经制作了一个广义差异,可以比较任何类型的2个对象,并且可以运行修改处理程序gist.github.com/bortunac“diff.js”,使用前者:

old_obj={a:1,b:2,c:[1,2]}
now_obj={a:2 , c:[1,3,5],d:55}

so property a is modified, b is deleted, c modified, d is added

所以属性a被修改,b被删除,c被修改,d被添加

var handler=function(type,pointer){
console.log(type,pointer,this.old.point(pointer)," | ",this.now.point(pointer)); 

}

}

now use like

现在使用像

df=new diff();
df.analize(now_obj,old_obj);
df.react(handler);

the console will show

控制台将显示

mdf ["a"]  1 | 2 
mdf ["c", "1"]  2 | 3 
add ["c", "2"]  undefined | 5 
add ["d"]  undefined | 55 
del ["b"]  2 | undefined 

#7


0  

You can create an object with keys as the unique value corresponding for each object in array and then filter each array based on existence of the key in other's object. It reduces the complexity of the operation.

您可以使用键创建一个对象作为对应于数组中每个对象的唯一值,然后根据其他对象中键的存在过滤每个数组。它降低了操作的复杂性。

ES6

ES6

let a = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal"},  { value:"a63a6f77-c637-454e-abf2-dfb9b543af6c", display:"Ryan"}];
let b = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer", $$hashKey:"008"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed", $$hashKey:"009"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi", $$hashKey:"00A"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal", $$hashKey:"00B"}];

let valuesA = a.reduce((a,{value}) => Object.assign(a, {[value]:value}), {});
let valuesB = b.reduce((a,{value}) => Object.assign(a, {[value]:value}), {});
let result = [...a.filter(({value}) => !valuesB[value]), ...b.filter(({value}) => !valuesA[value])];
console.log(result);

ES5

ES5

var a = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal"},  { value:"a63a6f77-c637-454e-abf2-dfb9b543af6c", display:"Ryan"}];
var b = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer", $$hashKey:"008"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed", $$hashKey:"009"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi", $$hashKey:"00A"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal", $$hashKey:"00B"}];

var valuesA = a.reduce(function(a,c){a[c.value] = c.value; return a; }, {});
var valuesB = b.reduce(function(a,c){a[c.value] = c.value; return a; }, {});
var result = a.filter(function(c){ return !valuesB[c.value]}).concat(b.filter(function(c){ return !valuesA[c.value]}));
console.log(result);

#8


-4  

If you are willing to use external libraries, You can use _.difference in underscore.js to achieve this. _.difference returns the values from array that are not present in the other arrays.

如果您愿意使用外部库,可以在underscore.js中使用_.difference来实现此目的。 _.difference返回数组中其他数组中不存在的值。

_.difference([1,2,3,4,5][1,4,10])

==>[2,3,5]