首页 > 解决方案 > 删除多维数组中的重复项

问题描述

我有这些数据,如何返回唯一数组 - 每个索引都没有重复的数组。

[ 
  [ 0, 1, 2 ], 
  [ 1, 0, 2 ], 
  [ 1, 1, 1 ], 
  [ 1, 2, 0 ], 
  [ 2, 0, 1 ], 
  [ 2, 1, 0 ] 
]

我想要的输出是这样的
0 1 2
1 2 0
2 0 1

标签: javascript

解决方案


这应该是你想要的。

console.clear()
arr = [ 
  [ 0, 1, 2 ], 
  [ 1, 0, 2 ], 
  [ 1, 1, 1 ], 
  [ 1, 2, 0 ], 
  [ 2, 0, 1 ], 
  [ 2, 1, 0 ] 
];

var res = arr.filter((duplicates = [], e => {
  // prefill duplicates with empty arrays
  e.forEach((k, i) => {
    duplicates[i] = duplicates[i] ||  [];
  })
  // check if there are duplicates and then set keep to false
  let keep = e.reduce((keep, val, i) => {
    return keep && (!duplicates[i].includes(val));
  }, true);
  // if keep, save this array to duplicates
  if (keep) {
    e.forEach((k, i) => {
      duplicates[i].push(k)
    })
  }
  return keep;
}))

res.forEach(k => {
  console.log(...k)
})
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读