Search code examples
javascriptarraysfilterlogical-operators

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

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 can use an object to represent the two categories, cats, using the Array#reduce method as in the following demo:

    const ages = [10, 15, 18, 21, 24, 30, 32];
    const cats = ages.reduce(
      (lists, age) => lists[age >= 18 ? 'above' : 'below'].push(age) && lists, {below:[],above:[]}
    );
    
    console.log( cats );

    With filter Method ...

    You can combine the two results into an object as follows:

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