简体   繁体   English

在javascript中从一组二维数组中提取偶数数组

[英]Extracting an array with even numbers out a bidimensional set of arrays in javascript

/ for the following bidimensional array im trying to write a function that finds the array composed by even numbers and then extract it / /对于下面的二维数组,我试图编写一个函数来查找由偶数组成的数组,然后提取它/

var loggedPasscodes =[
  [1, 4, 4, 1],
  [1, 2, 3, 1],
  [2, 6, 0, 8],
  [5, 5, 5, 5],
  [4, 3, 4, 3]
];

// I can check if its elements are even so: // 我可以检查它的元素是否相同:

if(loggedPasscodes[0][1]%2===0) {
  console.log(loggedPasscodes[0])
} else {
  console.log('nope')
}

//And I can loop the function to atleast give me the outer tier of the array like this: //并且我可以循环该函数以至少给我数组的外层,如下所示:

function getValidPassword(x){
  for(i=0;i<x.length;i++){
    console.log(x[i])
  }
};

console.log(getValidPassword(loggedPasscodes))

I would like to run the function and return the [2, 6, 0, 8] array.我想运行该函数并返回 [2, 6, 0, 8] 数组。 Thanks in advance for your time.在此先感谢您的时间。

You could find the array by checking each nested array with Array#every and if all values are even.您可以通过使用Array#every检查每个嵌套数组以及是否所有值都是偶数来找到数组。

 var loggedPasscodes = [[1, 4, 4, 1], [1, 2, 3, 1], [2, 6, 0, 8], [5, 5, 5, 5], [4, 3, 4, 3]], allEven = loggedPasscodes.find(a => a.every(v => v % 2 === 0)); console.log(allEven);

If you want more than the first found, you could filter the array.如果您想要的不仅仅是第一个找到的,您可以过滤数组。

 var loggedPasscodes = [[1, 4, 4, 1], [1, 2, 3, 1], [2, 6, 0, 8], [5, 5, 5, 5], [4, 3, 4, 3]], allEven = loggedPasscodes.filter(a => a.every(v => v % 2 === 0)); console.log(allEven);

I kept tinkering with the problem and found and alternative answer that runs 2 cycles on the array and displays every 4 consecutive matches.我一直在修补这个问题,并找到了在阵列上运行 2 个周期并每 4 个连续匹配显示的替代答案。 Nina's answer is better and more elegant, but I found this one interesting and i'll leave it here as an alternative. Nina 的答案更好更优雅,但我发现这个很有趣,我将把它留在这里作为替代方案。

  let loggedPasscodes = [
  [4, 3, 4, 4],
  [1, 2, 3, 7],
  [4, 6, 0, 8],
  [2, 2, 2, 2],
  [4, 4, 4, 4],
  [2, 2, 2, 2],
  [1, 3, 4, 5],
  [2, 2, 2, 2]
  ];




  function getValidPassword(x){

  var password =[];

  //main array cycle:
  for(ciclop=0;ciclop<x.length;ciclop++){
  //secondary array cycle:
    for (ciclos=0;ciclos<=4;ciclos++){

  //if it gets 4 matches in a row:
     if (password.length===4){
      console.log(password);
      password=[]; 
    }

  // if it is even:
  else if (x[ciclop][ciclos]%2===0) {
   password.push(x[ciclop][ciclos]); 
  }


 //if it is odd:
 else if(x[ciclop][ciclos]%2!==0){
  password=[];
     } 
    }
   }
  }
  getValidPassword(loggedPasscodes);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM