Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using && operator in javascript return statement

I am learning javascript and I was applying the filters in javascript code, In below code, is there any possibility to improvise this code ? i was hoping if someone could tell me to how to use only one variable to store result of ages which are greater than 18 and less than 18. is there possibilty to use && operator in single return statement ? So that in final result I can show the data as

Voters under 18,21,24,30,32 category can vote.
Voters under 10,15 category cannot vote

//Code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const ages = [10, 15, 18, 21, 24, 30, 32];
const ageResultabove = ages.filter((ageabove) => {
  return ageabove >= 18;
});
const ageResultbelow = ages.filter((ageabelow) => {
  return ageabelow < 18;
});
console.log(`Voters under ${ageResultabove} category can vote`);
console.log(`Voters under ${ageResultbelow} category cannot vote`);

Result should be like this
Voters under 18,21,24,30,32 category can vote.
Voters under 10,15 category cannot vote

>Solution :

You could take a function for checking adult ages and group by this result with true and false in a single loop.

const
    ages = [10, 15, 18, 21, 24, 30, 32],
    isAdult = age => age >= 18,
    result = ages.reduce((accumulator, age) => {
        accumulator[isAdult(age)].push(age);
        return accumulator
    }, { true: [], false: [] });

console.log(`Voters under ${result.true.join(', ')} category can vote`);
console.log(`Voters under ${result.false.join(', ')} category cannot vote`);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading