如何比较一个数组和一个数组的数组? [英] How to compare an array to an array of arrays?

查看:150
本文介绍了如何比较一个数组和一个数组的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是井字游戏应用程序中的尝试. 我有两个数组playerMoveswinningCombinations.像这样.

This is an attempt in a tic tac toe game app. I have two arrays playerMoves and winningCombinations. Like this.

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中的每个数组匹配.

I need to filter the winningCombination array such that at-least and at-most two values of playerMoves array matches with each array in 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;
      }        
    })
  })      
}

推荐答案

三个简单步骤:

  • 使用indexOf函数检查playerMoves数组中是否存在winningCombinations数组的子数组中的指定元素.
  • 如果是这样-使用Array#filter函数将其过滤掉.
  • 如果返回的经过过滤的子数组的长度等于2,则意味着出现了两个(不多,也更少)元素-它满足了我们的条件-再次用另一个Array#filter对其进行了过滤.
  • li>
  • Use indexOf function to check, if specified element from the subarray of winningCombinations array is present in the playerMoves array.
  • If so - filter it out with Array#filter function.
  • If the returned, filtered subarray has length equal to 2, it means that two (no more, nor less) elements have appeared - it fulfills our condition - filter it once again with yet another 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));

这篇关于如何比较一个数组和一个数组的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆