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

时间:2016-04-21 20:18:36

标签: javascript arrays

我是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);
      }
    }
  }
}

2 个答案:

答案 0 :(得分:6)

这是另一个潜在的解决方案:

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

答案 1 :(得分:1)

这是另一种可能的解决方案。公共值被推送到一个单独的数组中,也会从其初始数组中删除。

var finalSelective = ["CS348", "CS353", "CS381", "CS422", "CS448", "CS490-ES0", "CS490-DSO"],
finalSEelective = ["CS348", "CS352", "CS353", "CS354", "CS381", "CS422", "CS448", "CS456", "CS473", "CS490-DSO", "CS490-ES0"],
SEelecSelec = [],
el, index;

for (var i = 0, len = finalSelective.length; i < len; i++) {
    el = finalSelective[i];

    index = finalSEelective.indexOf(el);

    if (index > -1) {
        SEelecSelec.push(el);
        finalSEelective.splice(index, 1);
        finalSelective.splice(i, 1);
    }
}

console.log(finalSelective, finalSEelective, SEelecSelec);

Plunker here