简体   繁体   中英

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. 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.

 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. Nina's answer is better and more elegant, but I found this one interesting and i'll leave it here as an alternative.

  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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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