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,826
  • 17
  • 80
  • 143

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
  • 33,468
  • 7
  • 37
  • 75
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
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
  • 33,468
  • 7
  • 37
  • 75
David Vicente
  • 3,091
  • 1
  • 17
  • 27