JavaScript. How to Compare Input Arrays

后端 未结 6 1998
隐瞒了意图╮
隐瞒了意图╮ 2021-01-15 14:13

I\'m stuck with this problem for 3 days now... Someone please help me.

Challenge 5
Construct a function intersection

6条回答
  •  不思量自难忘°
    2021-01-15 14:33

    Reduce the arrays to a Map of counts, with the value as key. Spread the Map to entries. Use Array.filter() on the Map's entries to remove all entries, which value is not equal to the arrayOfArrays lenth. Extract the original number from the entries using Array.map():

    function intersection(arrayOfArrays) {
      return [...arrayOfArrays.reduce((r, s) => {
        s.forEach((n) => r.set(n, (r.get(n) || 0) + 1));
        
        return r;
      }, new Map())]
      .filter(([k, v]) => v === arrayOfArrays.length)
      .map(([k]) => k);
    }
    
    console.log(intersection([[5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]]));

提交回复
热议问题