Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

187
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!