将differents元素仅转换为一个数组

时间:2019-02-18 12:29:40

标签: javascript

我正在尝试在单个数组中显示多个元素。 (请参见示例)

但是我不知道该怎么做...

感谢您的帮助

我显示我的脚本:

****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' ] ]

1 个答案:

答案 0 :(得分:0)

签出。使用Array#reduce

按照您期望的格式重新创建最终数组值
  1. 将第一个子数组推入新数组a
  2. 然后用新创建的数组b循环每个a子数组
  3. 使用forloop来打破循环
  4. 如果新数组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);