我有四个列表 - 两个用户,两个用于组。我必须检查在第一个用户列表中他们是用户,这些用户不在第二个列表中。
我的代码:
importPackage(java.io);
importPackage(java.lang);
var list1 = "Han SOLO, Luke SKYWALKER, Darth VADER, Boba FETT".split(', ')
,list2 = "Luke SKYWALKER, Han SOLO, Lando CALRISSIAN, Boba FETT".split(', ')
// group lists
,group1 = "Group1, Group1, Group1, Group2".split(', ')
,group2 = "Group1, Group1, Group2, Group2".split(', ')
,j = 0
,msg = "";
for(var j = 0; j < list2.length; j++) {
if (list1.indexOf(list2[j]) == -1)
msg = msg + list1[j] + " has been added to " + group1[j] + "<br />";
}
print(msg);
此代码的结果是:
Darth VADER已被添加到Group1
这个结果对我有好处,但是当我做出改变时:
var list1 = "Han SOLO, Luke SKYWALKER, Darth VADER, Boba FETT".split(', ')
,list2 = "Luke SKYWALKER, Han SOLO, Darth VADER, Boba FETT".split(', ')
// group lists
,group1 = "Group1, Group1, Group1, Group2".split(', ')
,group2 = "Group1, Group1, Group2, Group2".split(', ')
结果为空,但应该是:
Darth VADER已被添加到Group1
我想知道我应该改变什么,以纠正第二个脚本(两个用户列表相同)。
答案 0 :(得分:2)
你可以在检查前做一些准备:
1)用户分组
function group(users, groups) {
var result = {};
for (var i = 0; i < users.length; i++) {
var user = users[i];
if (!result[user]) result[user] = {};
result[users[i]][groups[i]] = true;
}
return result;
}
2)检查组不同于
function comp(one, two) {
function getGroups(u) {
var groups = [];
for (var i in u) groups.push(i);
return groups;
}
var res = {};
for (var i in one) {
if (!two[i]) {
res[i] = getGroups(one[i]);
} else {
var g = [],
g1 = one[i],
g2 = two[i];
for (var j in g1) {
if (!g2[j]) g.push(j);
}
res[i] = g;
}
}
return res;
}
结果我们有像
这样的对象{
"Han SOLO": [],
"Luke SKYWALKER": [],
"Darth VADER": [
"Group1"
],
"Boba FETT": []
}
因此,通过简单的循环,我们可以获得有关不同的所有信息,如
var msg = '';
for (var i in res) {
if (res[i].length) {
msg += 'user ' + i + ' added in group: ' + res[i].join() + '<br>';
}
}
var list1 = "Han SOLO, Luke SKYWALKER, Darth VADER, Boba FETT".split(', '),
list2 = "Luke SKYWALKER, Han SOLO, Darth VADER, Boba FETT".split(', ')
// group lists
,
group1 = "Group1, Group1, Group1, Group2".split(', '),
group2 = "Group1, Group1, Group2, Group2".split(', ');
function group(users, groups) {
var result = {};
for (var i = 0; i < users.length; i++) {
var user = users[i];
if (!result[user]) result[user] = {};
result[users[i]][groups[i]] = true;
}
return result;
}
function comp(one, two) {
function getGroups(u) {
var groups = [];
for (var i in u) groups.push(i);
return groups;
}
var res = {};
for (var i in one) {
if (!two[i]) {
res[i] = getGroups(one[i]);
} else {
var g = [],
g1 = one[i],
g2 = two[i];
for (var j in g1) {
if (!g2[j]) g.push(j);
}
res[i] = g;
}
}
return res;
}
var res = comp(group(list1, group1), group(list2, group2));
var msg = '';
for (var i in res) {
if (res[i].length) {
msg += 'user ' + i + ' added in group: ' + res[i].join() + '<br>';
}
}
document.getElementById('res').innerHTML = msg;
<p id="res"></p>