合并/展平多维数组并删除重复的Javascript

时间:2016-08-11 10:47:01

标签: javascript arrays multidimensional-array

我有一个多维数组,如下所示:

[Object, Object, 0, Object, 0]

我想展平/合并数组并删除重复项。结果应如下所示:

{{1}}

是否可以执行?

4 个答案:

答案 0 :(得分:2)

我的理解是你想在给定的列中保留第一个遇到的对象(如果存在)。

您可以使用.map().reduce()

执行此操作



var workouts = [
  [0, {id:1}, 0, 0, 0],
  [{id:2}, 0, 0, 0, 0],
  [0, 0, 0, {id:3}, 0]
];

var res = workouts.reduce(function(a, b) {
  return b.map(function(e, i) { return a[i] instanceof Object ? a[i] : e; });
}, []);


console.log(JSON.stringify(res));




答案 1 :(得分:0)

var workouts = [
  [0, {id:1}, 0, 0, 0],
  [{id:2}, 0, 0, 0, 0],
  [0, 0, 0, {id:3}, 0]
];

function flattenArray (array){
  var newArray = [];
  for (i=0; i<array.length; i++){
    var subArray = array[i];
    for (ii=0; ii<subArray.length; ii++){
      if (newArray.indexOf(subArray[ii]) == -1){
      newArray.push(subArray[ii]);
      }
    }
  }
  return newArray;
}
console.log(flattenArray(workouts));

http://codepen.io/anon/pen/WxLrqL

答案 2 :(得分:0)

我会喜欢这个;

   addSkillButon._default=function(x,target){
                 console.log("Case Statement switched to default");
                 console.log(skill.category);
  }; 
  addSkillButon.Attack=function(x,target){
      target.insertBefore(x, target.children[0]);
  } 

答案 3 :(得分:0)

晚会,但我仍然想利用:

下面是代码和鼓舞人心的帖子12

const myArray = [
  [0, {id:1}, 0, 0, 0],
  [{id:2}, 0, 0, 0, 0],
  [0, 0, 0, {id:2}, 0]
]

const myFlatArray = myArray.flat()
const result = [...new Set(myFlatArray.map(JSON.stringify))].map(JSON.parse)

console.log(JSON.stringify(result))

注意:此解决方案必须支持ES6

相关问题