我需要在一组数组中找到第一个公共元素。阵列的数量可以变化,但它们总是按顺序排列(小 - >大)。我的数组都是myObj的属性。
这是我到目前为止所做的:
function compare(myObj,v,j) {
if (myObj[j].indexOf(v)>-1) return true;
else return false;
}
function leastCommon ([1,5]) {
var myObj = { //This is filled by code, but the finished result looks like this
1: [1, 2,...,60,...10k]
2: [2, 4,...,60,...20k]
3: [3, 6,...,60,...30k]
4: [4, 8,...,60,...40k]
5: [5,10,...,60,...50k]
};
var key = [1,2,3,4,5]; //also filled by code
var lcm = myObj[key[key.length-1]].forEach(function(v) { //Iterate through last/largest multiple array
var j=key[key.length-2];
while (j>=0) {
if (compare(myObj,v,j)) { //check to see if it is in the next lower array, if yes, check the next one.
j--;
}
if (j>0 && (compare(myObj,v,j+1))===true) return v; //before the loop exits, return the match
}
});
return lcm;
}
我不确定是什么问题,但它返回未定义。
注意:是的,我知道forEach返回undefined,我尝试修改我的代码,并且我的编辑器出现“潜在的无限循环”错误。修改后的代码如下所示:
function leastCommon ([1,5]) {
var myObj = { //This is filled by code, but the finished result looks like this
1: [1, 2,...,60,...10k]
2: [2, 4,...,60,...20k]
3: [3, 6,...,60,...30k]
4: [4, 8,...,60,...40k]
5: [5,10,...,60,...50k]
};
var key = [1,2,3,4,5]; //also filled by code
var lcm = 0;
myObj[key[key.length-1]].forEach(function(v) { //Iterate through last/largest multiple array
var j=key[key.length-2];
while (j>=0) {
if (compare(myObj,v,j)) { //check to see if it is in the next lower array, if yes, check the next one.
j--;
}
if (j>0 && (compare(myObj,v,j+1))===true) lcm = v; //before the loop exits, set lcm = v
}
});
return lcm;
}
答案 0 :(得分:0)
我不会使用forEach,因为当您找到第一个匹配/失败时无法退出该方法。你需要保持循环。相反,你应该查看每个和indexOf的常规for循环。此代码还假定数组已排序,因此最小的数字首先出现。如果没有,带有数组克隆的简单sort()可以解决这个问题。
//pass in arrays, assumes array is sorted
function getFirstCommon (arrs) {
//Loop over the elements in the first array
for (var i=0; i<arrs[0].length; i++) {
//get the value for the current index
var val = arrs[0][i];
//make sure every array has the value
//if every does not find it, it returns false
var test = arrs.every( function (arr) {
//check the array to see if it has the element
return arr.indexOf(val)!==-1;
});
//If we find it, than return the current value
if (test) {
return val;
}
}
//if nothing was found, return null
return null;
}
//test numbers
var nums = [
[1,2,3,4,5,6],
[2,3,4,5,6],
[3,4,5,6],
[4,5,6,7,8,9],
[6,7,8,9]
];
console.log(getFirstCommon(nums)); //6
var nums2 = [
[1,2,3,4,5,6],
[2,3,4,5,6],
[3,4,5,6],
[4,5,6,7,8,9],
[5,7,8,9]
];
console.log(getFirstCommon(nums2)); //5
var nums3 = [
[1,2,3,4,5,6],
[7,8,9,10,11,12],
[7,8,9,10,11,12]
];
console.log(getFirstCommon(nums3)); //null
可以在不自行检查的情况下改进代码
答案 1 :(得分:0)
首先,你确实有一个无限循环。如果第一个compare()
失败,您永远不会减少j
,并继续检查相同的数字。
第二:你key
数组永远不会减少,所以你总是比较最后两个数组。