1

I have two array variables A and B.

A = [1,2,3,4]
B = [1,3,4,5,7,8]

How do I use filter in array B which has same element in A like B = [1,3,4]?

Aleksey Solovey
  • 4,153
  • 3
  • 15
  • 34
Raghul
  • 213
  • 1
  • 5
  • 9
  • 2
    Possible duplicate of [Simplest code for array intersection in javascript](https://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript) – Redu Jun 11 '18 at 11:26

3 Answers3

3

Use Array#filter with Array#includes:

const A = [1,2,3,4];
let B = [1,3,4,5,7,8];

B = B.filter(item => A.includes(item));
console.log(B);
31piy
  • 23,323
  • 6
  • 47
  • 67
0

You can also get your required result using filter() and indexOf

DEMO

let A = [1,2,3,4],
      B = [1,3,4,5,7,8];

let result = B.filter(v => A.indexOf(v) >= 0);

console.log(result);
.as-console-wrapper {max-height: 100% !important;top: 0;}
Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
0

You can use Array.prototype.filter along with Array.prototype.indexOf

array1.filter(value => -1 !== array2.indexOf(value));
nbirla
  • 600
  • 3
  • 14