代码之家  ›  专栏  ›  技术社区  ›  Omar

解析数组并返回公共交点

  •  -1
  • Omar  · 技术社区  · 6 年前

    我有一个这样的阵列

        arrays = [
            ['a', 'b', 'c', 'd'],
            ['a', 'b', 'c', 'g'],
            ['a', 'b', 'c', 'g', 'x'],
        ]
    

        function get_intersects(arrays) {
            // return all intersections
            return ['a', 'b', 'c', 'g'];
        }
    

    注意如何 g

    这是我的尝试但是 不见了。

    arrays = [
        ['a', 'b', 'c', 'd'],
        ['a', 'b', 'c', 'g'],
        ['a', 'b', 'c', 'g', 'x'],
    ]
    
    function get_intersects(arrays) {
        return arrays.shift().filter(function (v) {
            return arrays.every((a) => a.indexOf(v) !== -1 );
        });
    }
    
    
    
    console.log(get_intersects(arrays))
    2 回复  |  直到 6 年前
        1
  •  3
  •   Mark    6 年前

    如果您的目标是确定单个字母是否至少在数组中的2个中,则可以对它们进行计数。不清楚内部数组是否可以重复 ['a', 'b', 'c', 'g', 'x', 'x'] . 假设这些表示集合,并且不会有重复的成员,这只是计数和筛选计数大于1的任何内容的问题:

    var arrays = [
        ['a', 'b', 'c', 'g'],
        ['a', 'b', 'c', 'd'],
        ['a', 'b', 'c', 'g', 'x'],
    ]
    
    var counts = arrays.reduce((counts, arr) => {
        arr.forEach(c => counts[c] = (counts[c] || 0) + 1)
        return counts
    }, {})
    
    let common = Object.keys(counts).filter(k => counts[k] > 1)
    console.log(common)

    可以 如果有重复,可以在迭代和计数之前使用集合使其唯一。类似于:

    new Set(arr).forEach(c => counts[c] = (counts[c] || 0) + 1)
    
        2
  •  4
  •   Akrion    6 年前

    你也可以用 Set 具有 Array.filter Array.lastIndexOf

    let data = [ ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'g'], ['a', 'b', 'c', 'g', 'x'] ]
    
    let result = [...new Set(data.flat().filter((x,i,a) => a.lastIndexOf(x) != i))]
    
    console.log(result)
        3
  •  2
  •   Ammar    6 年前

    在遍历数组时,可以使用helper数组来放置您访问过的值。

    const arrays = [
      ['a', 'b', 'c', 'd'],
      ['a', 'b', 'c', 'g'],
      ['a', 'b', 'c', 'g', 'x'],
    ];
    
    const magic = arrays => {
      const values = [];
      const res = [];
      arrays.forEach(array => {
        array.forEach(e => {
          // if the current value has been visited and is not yet inserted into result array
          if (values.indexOf(e) !== -1 && res.indexOf(e) === -1) res.push(e);
          // if the current value hasn't been visited yet
          if (values.indexOf(e) === -1) values.push(e);
        });
      });
      return res;
    };
    
    console.log(magic(arrays));
        4
  •  1
  •   Slai    6 年前

    var arrays = [ ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'g'], ['a', 'b', 'c', 'g', 'x'] ]
    
    console.log( [...new Set(arrays.flat().sort().filter((v, i, a) => v == a[--i]))] )