我有四个列表-两个用于用户,两个用于组。我必须检查第一用户列表中的用户是否是第二列表中的用户。
我的代码:
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已添加到组1
这个结果对我来说是好的,但是当我进行更改时:
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已添加到组1
我想知道应该更改什么以更正第二个脚本(两个用户列表相同)。
最佳答案
您可以在检查之前做一些准备工作:
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>