-2

Note: Not a duplicate problem.. here I need to skip empty arrays.

Say I have several arrays like:

var a = [1, 2, 3, 4],
b = [2, 4],
c = [],
d = [4];

Using following function, I could get the desired result: [4]

var a = [1, 2, 3, 4],
  b = [2, 4],
  c = [],
  d = [4];

var res = [a, b, c, d].reduce((previous, current) =>
  !previous.length || previous.filter((x) => !current.length || current.includes(x)),
);

console.log(res)

I included !current.length || above to bypass empty array c. But this doesn't work if first array in the collection i.e. a is empty. The result would be [].

mplungjan
  • 169,008
  • 28
  • 173
  • 236
benjamin54
  • 1,280
  • 4
  • 28
  • 48

2 Answers2

1

Just filter. Makes the code much more readable

var a = [1, 2, 3, 4],
  b = [2, 4],
  c = [],
  d = [4];

var res = [c, b, a, d].filter(arr => arr.length).reduce((previous, current) =>
   previous.filter((x) => current.includes(x)),
);

console.log(res)
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

This code will work as you expected (vanilla JS, support old browsers):

var a = [1, 2, 3, 4],
  b = [2, 4],
  c = [],
  d = [4];

var res = [a, b, c, d].reduce(function(acc, arr) {
    // ignore empty array
    if(arr.length == 0) return acc;
    
    // assign first non-empty array to accumudation
    if(acc.length == 0) return arr;
    
    // otherwise, accumudation will be insection of current accomudation and current array
    return acc.filter(function(n) {
       return arr.indexOf(n) !== -1;
    });
  }, []);

console.log(res)
Quyết
  • 502
  • 5
  • 12