Avinash Prabhakar Avinash Prabhakar - 6 months ago 8x
Javascript Question

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]) {
var x = finalSelective.indexOf(finalSelective[i]);
if (x != -1) {
x = finalSEelective.indexOf(finalSEelective[j]);
if (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){
    a.splice(i, 1);
    b.splice(indexInB, 1);

JsBin with the code above only