0

Maybe by title seems a easy question, but I didn´t know how to do the shortest title for my question.
I want to delete elements from array on javascript, yes, but what I am looking for exactly is delete from array mismatched elements with other array on javascript (maybe it could be title, but too large).
For example:

Array A=> [a, b, c, d]  
Array B=> [b,d]  
Array C = deleteMismatchedElements(A,B)  
Array C (after function)-> [b,d]

I suppose that using a nested foreach loop it could be possible, but I wonder if there is a better way, something as a "native" implemented method that could be called, or similar...

Thank you very much.

Eloy Fernández Franco
  • 1,350
  • 1
  • 24
  • 47

1 Answers1

3
var C = [];
for(var i = 0; i < B.length; i ++){
    if(A.indexOf(B[i]) > -1){
        C.push(B[i]);
    }
}

What this does is

  1. Creates array C
  2. Runs through each item in B
  3. if B[i] is in A, add it to C
raumaan kidwai
  • 356
  • 1
  • 4
  • 14