[英]Transform differents element into array in only one array
我正在嘗試在單個數組中顯示多個元素。 (見示例)
但我不知道該怎么做......
謝謝你的幫助
我顯示我的腳本:
****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' ] ]
看看這個。使用Array#reduce
按預期格式重新創建最終數組值
a
a
循環每個b
子數組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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.