gpt4 book ai didi

javascript - 在单独的数组中显示两个数组的相同元素

转载 作者:搜寻专家 更新时间:2023-11-01 05:21:27 26 4
gpt4 key购买 nike

我对 JavaScript 很陌生。我在这里试图实现的是将两个数组中所有相同的元素放入另一个数组中。然后我删除原始两个数组中的那些元素。

但是,单独的数组并没有显示所有相同的元素。而且,两个数组仍然显示了一些相同的元素。不确定我哪里出错了。

以下代码可能有语法错误。我不得不对其进行修改,使其更易于提问。

var finalSelective = ["CS348", "CS353", "CS381", "CS422", "CS448", "CS490-ES0", "CS490-DSO"];
var finalSEelective = ["CS348", "CS352", "CS353", "CS354", "CS381", "CS422", "CS448", "CS456", "CS473", "CS490-DSO", "CS490-ES0"];
var SEelecSelec = []; //fulfills SE elective and S elective.
for (var i = 0; i < finalSelective.length; i++) { //There is something wrong with this one.
for (var j = 0; j < finalSEelective.length;j++){ //It does not show the correct repeats.
if (finalSelective[i] == finalSEelective[j]) {
SEelecSelec.push(finalSEelective[j]);
var x = finalSelective.indexOf(finalSelective[i]);
if (x != -1) {
finalSelective.splice(x,1);
}
x = finalSEelective.indexOf(finalSEelective[j]);
if (x != -1) {
finalSEelective.splice(x,1);
}
}
}
}

最佳答案

这是另一种可能的解决方案:

JsBin With Logging

var a = ["CS348", "CS353", "CS381", "CS422", "CS448", "CS490-ES0", "CS490-DSO"];
var b = ["CS348", "CS352", "CS353", "CS354", "CS381", "CS422", "CS448", "CS456", "CS473", "CS490-DSO", "CS490-ES0"];

var c = a.concat(b).filter(function(el) {
return a.indexOf(el) > -1 && b.indexOf(el) > -1;
});

编辑:根据您在下面的评论,获得实际所需输出的代码是:

for (var i = 0; i < a.length; i++) {
var indexInB = b.indexOf(a[i]);
if (indexInB > -1){
output.push(a[i]);
a.splice(i, 1);
b.splice(indexInB, 1);
i--;
}
}

JsBin with the code above only

关于javascript - 在单独的数组中显示两个数组的相同元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36779638/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com