简体   繁体   中英

Showing identical elements of two arrays in a separate array

I am quite new to JavaScript. What I am trying to achieve here is to put all the identical elements of two array into another array.I then delete those elements in the original two arrays.

However, the separate array does not show all the identical ones.Also, the two arrays still show some identical elements. Not sure where I went wrong.

The following code may have syntax errors. I had to modify it to make it easier to ask.

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

Here is another potential solution:

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

Edit: Per your comment below, the code to get your actual desired output is:

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

Here another possible solution. Common values are pushed in a separate array and also get removed from their initial arrays.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM