我有一个二维数组,每个维中有任意数量的元素,所以它是[m] [n]数组,但第二维长度(n
)是可变的。查找数组不工作的交集?
第二维中的每个元素都包含一个数字,并且在所有维中只会存在一个数字。
因此,例如,该阵列可以是:
[
[
126,
131,
138,
139,
140,
143
],
[
126,
201
]
]
记住m
可以> 2.
这里是我的代码:
var theArray = [
[126, 131, 138, 139, 140, 143],
[126, 201]
];
for(var i = 0; i < theArray.length; i++) // loop through each array of numbers
{
$.each(theArray[i], function(index, value) // loop through all of the numbers in this array
{
var nextArray = (i+1<theArray.length?theArray[i+1]:theArray[0]);
if($.inArray(value, nextArray) == -1) // if this number is not in the next array
{
console.log("removing index: " + index + ", value: " + value);
theArray[i].splice(index, 1); // remove the number from the array
}
});
}
console.log(theArray);
输出是这:
removing index: 1, value: 131
removing index: 2, value: 139
removing index: 3, value: 143
removing index: 4, value: undefined
removing index: 5, value: undefined
removing index: 1, value: 201
Array
[
[
126,
138,
140,
],
[
126
]
]
的jsfiddle:http://jsfiddle.net/hDL8K/
正如你所看到的,它几乎作品,但它无法删除两个值。
我认为这可能与index
在foreach
循环中增加每个循环和数组的大小减少,因为元素被删除,但我不知道。
为什么这不起作用,我该如何解决?
修改你通过迭代往往不能奏效的阵列,因为当你拼接的元素出来的它,其余元素的所有索引都会下移。 – Barmar
嗨Nate,我添加了一个不会修改原始数组的解决方案。 –