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

188
Visualizações
save different elements in array by a condition

How can I save elements in an array based on a condition? In the following array, if I pass an age, it returns the array with the elements that meet that condition, but if I pass an age that does not exist or nothing happens when calling the function, how can I add all the elements of array1 to array2

const array1 = [
  {
    name: 'jose',
    country: 'argentina',
    age: 20
  },
  {
    name: 'pedro',
    country: 'brazil',
    age: 18
  },
  {
    name: 'andrea',
    country: 'mexico',
    age: 20
  },
  {
    name: 'luis',
    country: 'eu',
    age: 19
  },
  {
    name: 'nancy',
    country: 'mexico',
    age: 18
  }
];
const getDatos = (age) => {
  const array2 = array2.filter(data=> data.age === age);
  console.log(array2 )
}
getDatos(20);
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use the ternary operator ? to check the length of array returned by filter. If any matches are found, return them, otherwise return all records.

const all = [
  { name: 'jose', country: 'argentina', age: 20 },
  { name: 'pedro', country: 'brazil', age: 18 },
  { name: 'andrea', country: 'mexico', age: 20 },
  { name: 'luis', country: 'eu', age: 19 },
  { name: 'nancy', country: 'mexico', age: 18 }
];

const getDatos = (age) => {
  let matches = all.filter(data => data.age === age);
  return (matches.length) ? matches : all;
}

console.log(getDatos(20)); // jose & andrea
console.log(getDatos(99)); // all records
about 4 years ago · Juan Pablo Isaza Relatório

0

not sure if this is what you want, but you can check if the age is in the array using Array.prototype.some(MDN documentation)

const getDatos = (age) => {
  if (array1.some(data => data.age === age)) {
    return array1.filter(data=> data.age === age);
  } else {
    return array1;
  }
}

EDIT: Based on Sebastian Simons comment, this approach it's better

const getDatos = (age) => {
  const results = array1.filter(data => data.age === age);

  return results.length > 0 ? results : array1;
}
about 4 years ago · Juan Pablo Isaza 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