我有一个二维数组,每个维度都有任意数量的元素,所以它是一个 [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/
如您所见,它几乎有效,但无法删除其中两个值。
我认为这可能与 foreach
循环中的 index
随着每个循环的增加和数组大小的减少有关,因为元素被删除了,但我'我不确定。
为什么这不起作用,我该如何解决?
最佳答案
Functional version with jQuery
var theArrays = [[126, 131, 138, 139, 140,143],[126, 201]],result = theArrays[0];
$.each(theArrays, function(index, currentArray) {
result = $.grep(result, function(currentElement) {
return currentArray.indexOf(currentElement) !== -1;
});
});
console.log(result);
简单的 JavaScript 版本:
var theArrays = [[126, 131, 138, 139, 140,143],[126, 201]],result = theArrays[0];
for (var i = 1; i < theArrays.length; i += 1) {
for (var j = 0; j < result.length; j += 1) {
if (theArrays[i].indexOf(result[j]) === -1) {
result.splice(j, 1);
j -= 1;
}
}
}
console.log(result);
输出
[ 126 ]
如果数组太大,那么最好将它们转换为对象,然后找到交集。因为对于较大的数组,对象中的项目查找会快得多。
var theObjects = [];
for (var i = 0; i < theArrays.length; i += 1) {
var tempObject = {};
for (var j = 0; j < theArrays[i].length; j += 1) {
tempObject[theArrays[i][j]] = true;
}
theObjects.push(tempObject);
}
var intersection = theObjects[0], result = [];
for (var i = 1; i < theArrays.length; i += 1) {
for (var key in intersection) {
if (theObjects[i].hasOwnProperty(key) === false) {
delete intersection[key];
}
}
}
for (var key in intersection) {
result.push(parseInt(key));
}
console.log(result);
关于javascript - 查找数组的交集不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20938328/