【问题标题】:How to compare an array to an array of arrays?如何将数组与数组数组进行比较?
【发布时间】:2017-12-22 10:51:54
【问题描述】:

这是一个井字游戏应用的尝试。 我有两个数组playerMoveswinningCombinations。像这样。

var playerMoves= [0,1,4];
var winningCombinations = [
        [0,1,2],[3,4,5],[6,7,8],
        [0,3,6],[1,4,7],[2,5,8],
        [0,4,8],[2,4,6]
      ];

我需要过滤winningCombination 数组,使playerMoves 数组的至少和最多两个值与winningCombination 中的每个数组匹配。

findPossibleMove(playerMoves);
// should return [[0,1,2],[1,4,7], [0,4,8] ]

我的尝试

function findPossibleMove(arr){
  var found = 0;
  return arr.forEach((item)=>{
    winningCombinations.map((obj)=>{
      if(obj.indexOf(item) !== -1) {
        found++;
      }
      if(found===2){
        return obj;
      }        
    })
  })      
}

【问题讨论】:

    标签: javascript arrays underscore.js lodash


    【解决方案1】:

    三个简单的步骤:

    • 使用indexOf 函数检查winningCombinations 数组的子数组中的指定元素是否存在于playerMoves 数组中。
    • 如果是这样 - 使用 Array#filter 函数将其过滤掉。
    • 如果返回的过滤子数组的长度等于2,则意味着出现了两个(不多也不少)元素 - 它满足我们的条件 - 再次使用另一个 Array#filter 过滤它。李>

    let playerMoves = [0, 1, 4];
    let winningCombinations = [
      [0, 1, 2],
      [3, 4, 5],
      [6, 7, 8],
      [0, 3, 6],
      [1, 4, 7],
      [2, 5, 8],
      [0, 4, 8],
      [2, 4, 6],
    ];
    
    let res = winningCombinations.filter(v => v.filter(c => {
      return playerMoves.indexOf(c) > -1;
    }).length == 2);
      
      console.log(JSON.stringify(res));

    【讨论】:

    • 你会怎么做而不是过滤掉不匹配的一次,替换它们。所以如果我有 [['WA', 0], [OR, 0] 并且另一个数组是 [['WA', 1], [OR, 0],我希望第一个数组中的 WA 被替换为第二个数组中的 WA 值。
    【解决方案2】:

    因为我们必须检查每个过滤数组中的长度(匹配项),如何跳过创建过滤数组对数组和reducing它到多个匹配元素并直接检查而不是@987654322 @?

    let playerMoves = [0, 1, 4];
    let winningCombinations = [
      [0, 1, 2],
      [3, 4, 5],
      [6, 7, 8],
      [0, 3, 6],
      [1, 4, 7],
      [2, 5, 8],
      [0, 4, 8],
      [2, 4, 6],
    ];
    let res = winningCombinations.filter(a=> a.reduce((r, v) => r + playerMoves.includes(v), 0)==2);
    
    console.log('matching array: ', res)

    【讨论】:

      【解决方案3】:

      您可以使用filterincludes 来实现:

      var playerMoves= [0,1,4];
      var winningCombinations = [
        [0,1,2],[3,4,5],[6,7,8],
        [0,3,6],[1,4,7],[2,5,8],
        [0,4,8],[2,4,6]
      ];
      
      var filteredCombinations = winningCombinations.filter((combination) =>
        combination.filter(x => playerMoves.includes(x)).length === 2);
      
      console.log(filteredCombinations);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-26
        • 2021-05-18
        • 2015-10-23
        • 1970-01-01
        • 2019-04-03
        • 1970-01-01
        • 2015-10-05
        • 1970-01-01
        相关资源
        最近更新 更多