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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With