0

There are multiple arrays

  1. [1,2,3]
  2. [2,3,4]
  3. [2,4,5]

Now I want to get the values that contain in all arrays. In this example it would be [2]. Is there an easy way to do this?

I tired https://stackoverflow.com/a/14438954/639035 however, if I try it with three arrays after each other, I get wrong results (4 would be included).

Update Posted answer works, the error was in another part of my code

Stefan
  • 14,332
  • 15
  • 75
  • 133

2 Answers2

2

You may use:

Example:

let a1 = [1, 2, 3];
let a2 = [2, 3, 4];
let a3 = [2, 4, 5];

let result = a1.filter(v => a2.includes(v) && a3.includes(v));

console.log(result);
Ele
  • 32,412
  • 7
  • 33
  • 72
Mohammad Usman
  • 34,173
  • 19
  • 88
  • 85
0

This will work:

let a = [1,2,3];
let b = [2,3,4];
let c = [2,4,5];

let result = a.reduce((total, elem) => {
    if((b.indexOf(elem) !== -1) && (c.indexOf(elem) !== -1)) {
        total.push(elem);
    }
    return total;
}, []);

console.log(result);
Ele
  • 32,412
  • 7
  • 33
  • 72
David Vicente
  • 2,981
  • 1
  • 16
  • 27