var result = [
[0, 0, 0, -2],
[0, 0, -2, 0],
[0, 0, 0, -2],
[0, 0, -2, 0],
[0, -2, 0, 0],
[0, -2, 0, 0],
[0, 0, 0, -2],
[0, 0, -2, 0],
[0, 0, 0, -2],
[0, 0, -2, 0],
[0, -2, 0, 0],
[0, -2, 0, 0],
[0, 0, 0, -2],
[0, 0, -2, 0],
[0, 0, 0, -2],
[0, 0, -2, 0],
[0, -2, 0, 0],
[0, -2, 0, 0],
[-2, 0, 0, 0],
[-2, 0, 0, 0],
[-2, 0, 0, 0],
[-2, 0, 0, 0],
[-2, 0, 0, 0],
[-2, 0, 0, 0]
];
for (var i = 0; i < result.length; i++) { //remove duplicates
var listI = result[i];
loopJ: for (var j = 0; j < result.length; j++) {
var listJ = result[j]; //listJ and listI point at different arrays within the result array
if (listI === listJ) continue; //Ignore itself
for (var k = listJ.length; k >= 0; k--) { //checks whether the values are different, if they are continue with the loop
if (listJ[k] !== listI[k]) continue loopJ;
}
// At this point, their values are equal so we remove from the result array
result.splice(j, 1);
}
}
document.getElementById("result").innerHTML = JSON.stringify(result);
<div id="result">
</div>
我正在尝试从我的程序在置换2d数组时创建的某些数据中删除重复项,但在某些情况下,它无法删除所有重复项。我有点迷失为什么,代码很短并且注释了,我在结果变量下的输入2d数组中进行了硬编码。
答案 0 :(得分:3)
https://jsfiddle.net/h26ro89p/2/
执行拼接时忘了回溯一个索引:
result.splice(j, 1);
j--;
为了防止将来出现这种情况,您可以反转循环甚至使用while循环。通过一些古老的英雄谷歌搜索,你可以在这里找到解决方案:
答案 1 :(得分:0)
我将使用lodash
添加更短的内容https://jsfiddle.net/h26ro89p/3/
var result = [[0,0,0,-2],[0,0,-2,0],[0,0,0,-2],[0,0,-2,0],[0,-2,0,0],[0,-2,0,0],[0,0,0,-2],[0,0,-2,0],[0,0,0,-2],[0,0,-2,0],[0,-2,0,0],[0,-2,0,0],[0,0,0,-2],[0,0,-2,0],[0,0,0,-2],[0,0,-2,0],[0,-2,0,0],[0,-2,0,0],[-2,0,0,0],[-2,0,0,0],[-2,0,0,0],[-2,0,0,0],[-2,0,0,0],[-2,0,0,0]];
document.getElementById("result").innerHTML = JSON.stringify(_.uniqWith(result, _.isEqual));
答案 2 :(得分:0)
检查这个小提琴https://jsfiddle.net/c2uk0xow/3/,你需要JQuery来使用$ .each函数。
var arr = [
[0, 0, 0, -2],
[0, 0, -2, 0],
[0, 0, 0, -2],
[0, 0, -2, 0],
[0, -2, 0, 0],
[0, -2, 0, 0],
[0, 0, 0, -2],
[0, 0, -2, 0],
[0, 0, 0, -2],
[0, 0, -2, 0],
[0, -2, 0, 0],
[0, -2, 0, 0],
[0, 0, 0, -2],
[0, 0, -2, 0],
[0, 0, 0, -2],
[0, 0, -2, 0],
[0, -2, 0, 0],
[0, -2, 0, 0],
[-2, 0, 0, 0],
[-2, 0, 0, 0],
[-2, 0, 0, 0],
[-2, 0, 0, 0],
[-2, 0, 0, 0],
[-2, 0, 0, 0]
];
var _tmp_arr = [];
var result = [];
$.each(arr, function(i,v)
{
if(!_tmp_arr.includes(JSON.stringify(v)))
{
_tmp_arr.push(JSON.stringify(v));
}
});
$.each(_tmp_arr, function(i,v)
{
result.push(JSON.parse(v));
});
注意:我必须转换为字符串,然后再次解析,以便比较两个结果。
[-2,0,0,0] === [-2,0,0,0]
返回false,但在我对其进行字符串化后,它为true,"[-2,0,0,0]" === "[-2,0,0,0]"
。