Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

110
Visualizações
Passing a variable to filter callback function

When passing a callback to filter. value, index and Array object is passed to the callback parameters, so how is it possible for me to create a reusable filter callback where i can pass any animal type and filter accordingly.

I did look at How do I pass an extra parameter to the callback function in Javascript .filter() method? but could not get it to work as intended

let animals = [
  { name: "fiddo", type: "dog" },
  { name: "garfield", type: "cat" },
  { name: "diddi", type: "bird" },
  { name: "bob", type: "cat" },
];

This is what i want to do, I know it is not possible, but how could i achive something "similar"?

function filterAnyAnimal(animal, index, arr, typeVariable) {
  if (animal.type === typeVariable) {
    return true;
  }
  return false;
}

console.log(animals.filter(filterAnyAnimal));

do i really have to do like this? or is there a way to pass a variable?


function isDog(animal) {
  if (animal.type === "dog") {
    return true;
  }
  return false;
}
almost 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

As felix-kling comment said and his already answer, you could do:

let animals = [
  { name: "fiddo", type: "dog" },
  { name: "garfield", type: "cat" },
  { name: "diddi", type: "bird" },
  { name: "bob", type: "cat" },
];
function filterAnyAnimal(typeVariable, animalType) {
   if (animalType === typeVariable) {
    return true;
  }
  return false;
}
let wordToFilter = 'cat';
console.log(animals.filter(function(element){
    return filterAnyAnimal(element.type, wordToFilter);
}));

almost 4 years ago · Santiago Trujillo Relatório

0

let animals = [
  { name: "fiddo", type: "dog" },
  { name: "garfield", type: "cat" },
  { name: "diddi", type: "bird" },
  { name: "bob", type: "cat" },
];

const result = animals.map(animal=>animal.type==="dog"?true:false);

console.log(result);

Map function can give you the desired result

almost 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda