Differencing sets an array of objects is a demand I encountered in the development, the scenario is this: the user first select the objects 1, 2, and OK to save into the database, the user enters the second time felt right , 3,4,5 selected object, and then saved to the database.
There is such a demand analysis: when the user selected a second time, do not do 3 is handled, 4,5 is to insert a new database, and 1 and 2 is to be deleted in the database, so that the database was to identify scripts identify and delete, or garbage data
For differencing sets an array of objects, what am I think there are other effective methods, the following is my approach, state of 3 indicates that the object is to be deleted
// 第一次选择
var temp = [{ id: "1", state: 1 }, { id: "2", state: 1 }, { id: "3", state: 1 }];
// 第二次选择
var selected = [{ id: "3", state: 1 }, { id: "4", state: 1 }, { id: "5", state: 1 }];
// 最终保存
var save = [];
function test() {
for (var i = 0; i < temp.length; i++) {
var flag = false;
for (var j = 0; j < selected.length; j++) {
if (temp[i].id == selected[j].id) {
flag = false;
break;
}
else {
flag = true;
}
}
if (flag) {
temp[i].state = 3;
save.push(temp[i]);
}
}
for (var i = 0; i < selected.length; i++) {
var flag = false;
for (var j = 0; j < temp.length; j++) {
if (selected[i].id == temp[j].id) {
flag = false;
break;
}
else {
flag = true;
}
}
if (flag) {
save.push(selected[i]);
}
}
console.log("差集结果", save);
}
test();