数组对象差异 javascript angularjs
Array objects difference javascript angularjs
我有 2 个数组对象,我想得到它们之间的区别如下:
array1 = [{"name":"MPCC","id":"tool:mpcc"}, {"name":"APP","id":"tool:app"}, {"name":"AII","id":"tool:aii"}, {"name":"VZZ","id":"tool:vzz"}, {"name":"USU","id":"tool:usu"}]
array2 = [{"name":"APP","id":"tool:app"}, {"name":"USU","id":"tool:usu"}]
result = [{"name":"MPCC","id":"tool:mpcc"}, {"name":"AII","id":"tool:aii"}, {"name":"VZZ","id":"tool:vzz"}]
代码如下:
$scope.initial = function(base, userData){
var result = [];
angular.forEach( base, function(baseItem) {
angular.forEach( userData, function( userItem ) {
if ( baseItem.id !== userItem.id ) {
if (result.indexOf(baseItem) < 0) {
result.push(baseItem);
}
}
});
});
return result;
}
$scope.initial(array1, array2);
上面代码的问题是我没有得到想要的结果。请让我知道出了什么问题。
与Angular无关。
你可以这样做:
var result = array1.filter(function(item1) {
for (var i in array2) {
if (item1.id === array2[i].id) { return false; }
};
return true;
});
或使用 ES6 语法:
var result = array1.filter(i1 => !array2.some(i2 => i1.id === i2.id));
我认为这与Angular本身无关。您正在寻找一种算法来计算两组之间的差异。
话题已经discussed. You may also be interested on this underscore plugin
我有 2 个数组对象,我想得到它们之间的区别如下:
array1 = [{"name":"MPCC","id":"tool:mpcc"}, {"name":"APP","id":"tool:app"}, {"name":"AII","id":"tool:aii"}, {"name":"VZZ","id":"tool:vzz"}, {"name":"USU","id":"tool:usu"}]
array2 = [{"name":"APP","id":"tool:app"}, {"name":"USU","id":"tool:usu"}]
result = [{"name":"MPCC","id":"tool:mpcc"}, {"name":"AII","id":"tool:aii"}, {"name":"VZZ","id":"tool:vzz"}]
代码如下:
$scope.initial = function(base, userData){
var result = [];
angular.forEach( base, function(baseItem) {
angular.forEach( userData, function( userItem ) {
if ( baseItem.id !== userItem.id ) {
if (result.indexOf(baseItem) < 0) {
result.push(baseItem);
}
}
});
});
return result;
}
$scope.initial(array1, array2);
上面代码的问题是我没有得到想要的结果。请让我知道出了什么问题。
与Angular无关。
你可以这样做:
var result = array1.filter(function(item1) {
for (var i in array2) {
if (item1.id === array2[i].id) { return false; }
};
return true;
});
或使用 ES6 语法:
var result = array1.filter(i1 => !array2.some(i2 => i1.id === i2.id));
我认为这与Angular本身无关。您正在寻找一种算法来计算两组之间的差异。
话题已经discussed. You may also be interested on this underscore plugin