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);
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
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;
}