Remove elements from javascript array

Maybe the title seems like a simple question, but I didn't know how to make the shortest title for my question.
I want to remove elements from an array in javascript, yes, but what I'm looking for is to remove mismatched elements from an array with another array in javascript (maybe it could be a name, but too big). For example:

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

      

I guess using a nested foreach loop might be possible, but I'm wondering if there is a better way, something like a "native" implemented method that could be named or similar ...

Many thanks.

0


source to share


1 answer


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

      

What does it mean,



  1. Creates an array C

  2. Runs through every element in B

  3. if

    B[i]

    is in A

    , add it toC

+3


source







All Articles