我正在尝试比较“item”数组和 copyofOpList 数组中的项目,以检索 copyofOpList 中的数据出现
这是我的尝试:
var _deleteUsedElement1 = function(item) {
for (var i = 0; i < item.length-1; i++){
for (var j = 0; j< $scope.copyofOpList.length-1; j++){
if (item[i].operationCode == $scope.copyofOpList[j].code) {
$scope.copyofOpList.splice(j, 1);
} } } };
$scope.compareArrays = function() {
...Get data from web Service
_deleteUsedElement1(item);
}
copyofOpList数组有14个元素,item数组有2个数组 但我的代码只删除一个事件(第一个),所以请问我如何更正我的代码,以检索与 item 数组相比的 copyofOpList 数组中的任何事件 感谢您的帮助
最佳答案
我会尽量避免在循环内循环 - 这既不是一种非常优雅也不是一种非常有效的方式来获得你想要的结果。
这里有一些更优雅且可能更高效的东西:
var item = [1,2], copyofOpList = [1,2,3,4,5,6,7];
var _deleteUsedElement1 = function(item, copyofOpList) {
return copyofOpList.filter(function(listItem) {
return item.indexOf(listItem) === -1;
});
};
copyofOpList = _deleteUsedElement1(item, copyofOpList);
console.log(copyofOpList);
//prints [3,4,5,6,7]
}
由于我刚刚注意到您正在比较对象属性,因此这里有一个过滤匹配对象属性的版本:
var item = [{opCode:1},{opCode:2}],
copyofOpList = [{opCode:1},{opCode:2},{opCode:3},{opCode:4},{opCode:5},{opCode:6},{opCode:7}];
var _deleteUsedElement1 = function(item, copyofOpList) {
var iOpCodes = item.map(function (i) {return i.opCode;});
return copyofOpList.filter(function(listItem) {
return iOpCodes.indexOf(listItem.opCode) === -1;
});
};
copyofOpList = _deleteUsedElement1(item, copyofOpList);
console.log(copyofOpList);
//prints [{opCode:3},{opCode:4},{opCode:5},{opCode:6},{opCode:7}]
以这种方式进行操作的另一个好处是,您可以避免在对阵列进行操作时修改阵列,这是 JonSG 和 Furhan S. 在其答案中提到的积极效果。
关于javascript - 从数组中删除数据与其他数组进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37748017/