How to filter an array and extract the values which are equal to another array in javascript?

I have an array from API which has lot of string values. I have another array which has the values I needed. How to extract only the values from the API array which matches my array.

API array1= ["abc", "xyz", "jkl", "lmk", "ajudsi" ...]; 
my array2 = ["abc", "jkl"]

I want to check each value of the API array1 with my array and filter the values which matches my array2.

My filtered array should be:

array1 = ["abc", "jkl"]

Any idea how to do this? Thanks.

1 answer

  • answered 2021-03-08 20:53 Evren

    You can use this approach to filter your match values

    var filterFunction = ["abc", "xyz", "jkl", "lmk", "ajudsi"].filter(
        function(e) {
          return this.indexOf(e) >= 0;
        ["abc", "jkl"]