我正在尝试在单个数组中显示多个元素。 (请参见示例)
但是我不知道该怎么做...
感谢您的帮助
我显示我的脚本:
****Du code******
var color = [];
var risk = [];
if(Operational.length == group.name.length){
color = "green";
risk = "Operational";
console.log(group.name);
// toto
// tata
// titi
}
if(Test.length > 0){
color = "";
risk = "";
}
if(PartialOutage.length > 0){
color = "orange"
risk = "Partial";
}
if(MajorOutage.length > 0){
color = "red";
risk = "Major ";
}
var Group = new Array(color,risk,group.name);
Groups.push(Group);
Groups.sort();
}
});
console.log(Groups);
}
**** Du code *****
实际结果:
[ [ 'green', 'Operational', 'toto' ],
[ 'green', 'Operational', 'tata' ],
[ 'green', 'Operational', 'titi' ],
[ 'orange', 'Partial', 'test' ],
[ 'red', 'Major ', 'test2' ] ]
预期结果:
[ [ 'green', 'Operational', 'toto,tata,titi' ],
[ 'orange', 'Partial', 'test' ],
[ 'red', 'Major ', 'test2' ] ]
答案 0 :(得分:0)
签出。使用Array#reduce
a
b
循环每个a
子数组forloop
来打破循环a
中存在子数组值,则合并两个数组并过滤重复的//Check the comments in snippet
var a = [
['green', 'Operational', 'toto'],
['green', 'Operational', 'tata'],
['green', 'Operational', 'titi'],
['orange', 'Partial', 'test'],
['red', 'Major ', 'test2']
];
a = a.reduce(function(a, b) {
for (var i = 0; i <= b.length; i++) {
var brk = false;
var check = true;
if (a.length > 0) {
a.forEach(function(k, ind) {
if (k.indexOf(b[i]) > -1) { //if contains same arg
k = k.concat(b); //join two array
var j = k.filter((l,n)=> k.filter(m=> m == l).length == 1).filter(o=>o)
a[ind] = k.filter((l, n) => k.indexOf(l) != n); // filter duplicate
a[ind].push(j.join(','))
brk = true; //then break the statement
check = true;
} else {
check = false; //its not contain any arg direct push child into new array
}
})
if (brk) {
break;
}
if (!check) {
a.push(b)
}
} else {
a.push(b);
}
}
return a // recreated new array return
}, []);
console.log(a);