简体   繁体   中英

Why filter function is returning array even when it does not pass the condition

I'm struggling to understand why this code is not working. its working with a small dataset though.

const gl = wList.GreateLeague
const data = JSON.parse(fs.readFileSync("./raw/data.json"))
    
(function () {
  let glFinds = data.pokemons.filter((poke) => gl.hasOwnProperty(poke.pokemon_id))
  let ax = glFinds.filter((p) => {
    return gl[p.pokemon_id].stats.filter((ammo) => {
      return (
        p.attack === ammo[0] && p.defence === ammo[1] && p.stamina === ammo[2]
      );
    });
  });
  console.log(glFinds)
  console.log(ax)
})();

my output for both console is same, therefore filter on ax is not working. ax is working fine if I include testData.json which is a smaller then data.json .

edit: stats look like this. here [0],[1],[2] are the attack defense and stamina

"stats": [
          [1, 15, 15, 20.5, 1494],
          [0, 13, 11, 20.5, 1494],
          [2, 14, 15, 20.5, 1494],
          [0, 10, 15, 20.5, 1494],
          [1, 12, 11, 20.5, 1494],
          [0, 15, 15, 20.5, 1494],
          [3, 13, 15, 20.5, 1494],
          [0, 14, 10, 20.5, 1494],
          [2, 15, 14, 20.5, 1494],
          [0, 11, 13, 20.5, 1494]
        ],

my data files have array of objects like this:

{
      "pokemon_id": 155,
      "attack": 2,
      "defence": 5,
      "stamina": 0,
      "move1": 209,
      "move2": 125,
      "level": 4,
    }

I am trying to filter any object that matches (0,1,2 index) of stats array, object's attack, defense and stamina must match any of the stats array first 3 element.

The function inside filter must return true or false , depending on whether the current item shall be included in the output array or not. But your function returns gl[p.pokemon_id].stats.filter(...) , which is an array, as Andreas already pointed out.

When trying to evaluate an array as true or false , it counts as true (even if it is empty), therefore your whole filter procedure effectively does nothing.

if ([]) console.log(true);
// true

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