我正在尝试提取departments数组中存在但dep_log中不存在的所有部门。我还想提取所有具有delete=1的部门。
注意:如果两个部门的id相同,并且deleted=1,我只想检索最新的一个,而不重复。
我尝试了这个方法,但得到了错误的结果:
var departments = [{
"department_id": "1",
"name": "sales"
}, {
"department_id": "2",
"name": "marketing"
}, {
"department_id": "3",
"name": "operation"
}];
var dep_logs = [{
"department_id": "2",
"creation_date": "2023-05-22 15:47:58",
"created_by": "1",
"deleted": "0"
}, {
"department_id": "2",
"creation_date": "2023-05-22 15:46:56",
"created_by": "1",
"deleted": "1"
}, {
"department_id": "3",
"creation_date": "2023-05-13 17:59:27",
"created_by": "1",
"deleted": "0"
}, {
"department_id": "2",
"creation_date": "2023-05-13 17:59:11",
"created_by": "1",
"deleted": "1"
}, {
"department_id": "1",
"creation_date": "2023-05-13 09:46:25",
"created_by": "1",
"deleted": "0"
}];
var finalList = []
var finalMapDeletedDepartment = []
var idSet = new Set();
dep_logs.forEach(item => {
idSet.add(item.department_id);
if (item.deleted === 1) {
if (finalMapDeletedDepartment.has(item.department_id)) {
var itemValue = finalMapDeletedDepartment.get(item.department_id);
if (itemValue.creation_date < item.creation_date) {
finalMapDeletedDepartment.set(item.department_id, item);
}
} else {
finalMapDeletedDepartment.set(item.department_id, item);
}
}
});
departments.forEach(item => {
if (!idSet.has(item.id)) {
finalList.push(item)
}
});
console.log(idSet);
console.log(finalMapDeletedDepartment.values());
console.log(finalList);
结果应存储在新数组中。
1条答案
按热度按时间lnvxswe21#
我认为这段代码可以完成这项工作:
获取未登录部门:
获取已删除的部门(不重复的和最近的部门):