我有此数据,我如何返回唯一数组 - 每个索引都没有重复的数组。
[
[ 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
这应该是您想要的。
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; }
尝试此
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)
})
尝试
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));
update
op唯一任务任务可以具有多个解决方案( @ninasholz在评论此答案中提到的是 - 例如例如,我们至少有两个独立的独特(从OP来描述)解决方案:
-
[0,1,2],[1,2,0],[2,0,1]
-
[1,0,2],[2,1,0]
OP示例中有趣的是,这两个解决方案都有不同数量的元素 - 我在此处询问有关找到最佳解决方案(最短或最长)的新问题。
此解决方案正在检查一个循环中每个数组的所有元素,如果您在每个数组中有三个元素(如您所示),那么此解决方案应该适用于您。
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)