Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

189
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda