我有此数据,如何返回唯一的数组-并非每个索引都重复的数组。
[
[ 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
答案 0 :(得分:2)
这应该是您想要的。
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; }
答案 1 :(得分:1)
尝试
let a= [ [0,1,2], [1,0,2], [1,1,1], [1,2,0 ], [2,0,1 ], [2,1,0 ] ];
let t=[{},{},{}];
let d= a.filter(e =>
!e.reduce((g,h,i)=> g||(e[i] in t[i]),false) && e.map((x,i) => t[i][x]=x)
);
console.log(JSON.stringify(d));
更新
OP唯一性任务可以有多个解决方案(@NinaSholz在对此答案的评论中提到了什么)-例如对于OP示例,我们至少有两个独立的独特(按OP的描述)解决方案:
[0,1,2],[1,2,0],[2,0,1]
[1,0,2],[2,1,0]
OP示例中有趣的是,这两个解决方案都有不同数量的元素-我问有关寻找最佳解决方案(最短或最长)here的新问题。
答案 2 :(得分:1)
尝试一下
let arr= [ [ 0, 1, 2 ], [ 1, 0, 2 ], [ 1, 1, 1 ], [ 1, 2, 0 ], [ 2, 0, 1 ], [ 2, 1, 0 ] ];
let index =[];
arr.forEach(function(element) {
element.forEach(function (value, i) {
if(index[i] == undefined)
{
var x = [value];
index[i]= x;
}
else if (index[i].indexOf(value) ==-1)
{
index[i].push(value);
}
});
});
index.forEach(k => {
console.log(...k)
})
答案 3 :(得分:0)
此解决方案是在一个循环中检查每个数组的所有元素,如果每个数组中有三个元素(如您所示),那么此解决方案应该对您有用。
var arr = [
[ 0, 1, 2 ],
[ 1, 0, 2 ],
[ 1, 1, 1 ],
[ 1, 2, 0 ],
[ 2, 0, 1 ],
[ 2, 1, 0 ]
]
var indicesToRemove = arr.reduce((acc, eachElem, index) => {
var isRemoveIndexPushed = false;
if (acc.firstIndex.length !== 0 && acc.firstIndex.indexOf(eachElem[0]) != -1) {
isRemoveIndexPushed = true
}
if (acc.secondIndex.length !==0 && acc.secondIndex.indexOf(eachElem[1]) != -1) {
isRemoveIndexPushed = true;
}
if (acc.thirdIndex.length !== 0 && acc.thirdIndex.indexOf(eachElem[2]) != -1) {
isRemoveIndexPushed = true
}
if (!isRemoveIndexPushed) {
acc.firstIndex.push(eachElem[0]);
acc.secondIndex.push(eachElem[1]);
acc.thirdIndex.push(eachElem[2]);
} else {
acc.removeIndex.push(index);
}
return acc;
}, {removeIndex: [], firstIndex: [], secondIndex: [], thirdIndex: []}).removeIndex;
var newArr = []
arr.forEach((elem, i) => {
if (i === indicesToRemove[0]) {
indicesToRemove.shift()
} else {
newArr.push(elem)
}
})
arr = newArr
console.log(arr)