function arraysCommon(array1, array2) {
return array1.filter(x => array2.includes(x));
}
此功能无法按我想要的方式工作。例如 givenarray1 = [1,2,3,2,1]
并且array2 = [5,4,3,2,1]
它返回[1,2,3,2,1]
,因为元素1,2,3
在两个数组中都可以看到。但我希望它按该顺序返回[1,2,3]
,因为1,2,3
只出现一次array2
并被视为单独的实体。
所以几乎功能应该是
我试图遍历数组并检查和比较每个数组中重复的数量,但我似乎无法让逻辑正常工作。有没有不同的方法来解决这个问题?
我附上了两个维恩图的图像,可以澄清差异
不幸的是,它变得更加复杂,因为您需要知道您已经添加了哪些数字。在这种情况下,您需要一个临时数组来保存结果。我们还需要两次跟踪数组中是否存在一个数字。
尝试这个:
function arraysCommon(array1, array2) {
//Copy array2 by duplicating and spreading the elements into another array.
var copyArray2 = [...array2];
//Temperary Array
var temp = [];
for (let x of array1) {
//Check if the element is in the first array and not already added to the temp array
if (copyArray2.includes(x)) {
temp.push(x);
//Remove item from copy array2 so it cannot be used anymore
copyArray2.splice(copyArray2.indexOf(x), 1);
}
}
//Return the temp array
return temp;
}
console.log(arraysCommon([1,2,3,2,1], [5,4,3,2,1]))
console.log(arraysCommon([1,2,3,2,1], [2,2,3,3,4]))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句