zoukankan      html  css  js  c++  java
  • js 多个数组取交集

    两个数组取交集:

    const intersection = (a, b) => {
      const s = new Set(b);
      return [...new Set(a)].filter(x => s.has(x));
    };

    用法:

    intersection([1, 2, 3], [4, 3, 2]); // [2, 3]

    多个数组取交集:

    方案一:循环遍历

    function intersection() {
      var result = [];
      var lists;
    
      if(arguments.length === 1) {
        lists = arguments[0];
      } else {
        lists = arguments;
      }
    
      for(var i = 0; i < lists.length; i++) {
        var currentList = lists[i];
        for(var y = 0; y < currentList.length; y++) {
            var currentValue = currentList[y];
          if(result.indexOf(currentValue) === -1) {
            var existsInAll = true;
            for(var x = 0; x < lists.length; x++) {
              if(lists[x].indexOf(currentValue) === -1) {
                existsInAll = false;
                break;
              }
            }
            if(existsInAll) {
              result.push(currentValue);
            }
          }
        }
      }
      return result;
    }

    方案二:实际还是循环遍历,不过代码看上去就简单多了:

    let arr = [
          [1, 2, 3, 4],
          [3, 4, 6],
          [4, 5],
          [4, 5, 8, 9],
          [4, 5, 2, 7],
          [4, 5, 3],
          [4, 5, 0],
        ];
    
    arr.reduce((a, b) => a.filter(c => b.includes(c))) // [4]
  • 相关阅读:
    观察者模式
    系统高并发网络图书室
    java keytool
    ant 脚本使用技巧
    Unsupported major.minor version 51.0 错误解决方案
    Oracle的网络监听配置
    win8 JDK环境变量不生效
    javax.mail
    xmlrpc
    网络时间同步
  • 原文地址:https://www.cnblogs.com/itachilee/p/14267986.html
Copyright © 2011-2022 走看看