2

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

  • @Pointy most of (if not all) the engines will convert it to number before comparing – Konrad Dec 11 '22 at 17:10
  • 1
    Also, I don't see that `&&` has anything to do with what you want. One way or another you need two separate lists for the output you want. – Pointy Dec 11 '22 at 17:11
  • This question is more like **How to get not matched elements with filter?** – Konrad Dec 11 '22 at 17:12
  • You could put the two values into an object with 'above' and 'below' properties, and return the object. – James Dec 11 '22 at 17:12
  • @Konrad Oh yea you're right; it's `+` that's weird like that. – Pointy Dec 11 '22 at 17:15
  • 2
    Relational operators like `<` and `>=` will coerce both arguments to a number if at least one of them is a number. Anyway, you can use [`group`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/group) (as of 2022, you’ll need a polyfill, linked at the bottom in the documentation): `const { ageResultAbove, ageResultBelow } = ages.group((age) => (age < 18 ? "ageResultBelow" : "ageResultAbove"));`. – Sebastian Simon Dec 11 '22 at 17:15
  • @SebastianSimon yes sorry, I apparently have not had enough coffee today. – Pointy Dec 11 '22 at 17:15
  • The desired result of `Voters under 18,21,24,30,32 category can vote` doesn't seem to make any sense. – jarmod Dec 11 '22 at 18:41

4 Answers4

0

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`);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Your output is totally fine, But i wanted to get same output using filter. Because I want to learn how one filter can be used for getting result of two categories (age above 18 and age below 18). – mohit_pamma Dec 11 '22 at 17:55
  • you did already. – Nina Scholz Dec 11 '22 at 17:58
  • is there any posibility to use this code. const ages = [10, 15, 18, 21, 24, 30, 32]; const ageResultAbove, ageResultBelow = ages.filter((ageabove, ageBelow) => { return (ageabove >= 18) and (ageBelow < 18); }); console.log(`Voters under ${ageabove} category can vote` + `Voters under ${ageBelow} category cannot vote`); – mohit_pamma Dec 11 '22 at 17:58
  • with [`Array#filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter), you get only a single array as result. and your callback does not work like this, the first parameter is onle of the items, the second is the index. please have a look to the link. – Nina Scholz Dec 11 '22 at 18:01
0

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`);
PeterKA
  • 24,158
  • 5
  • 26
  • 48
  • thanks for the input, I was looking to do it by using filter method but yeah the way you showed it using reduce method is also good. I will use this. – mohit_pamma Dec 12 '22 at 19:46
  • I can add the modification you would need for your own solution. – PeterKA Dec 12 '22 at 23:24
-1

Firstly, you are trying to compare string datatype with a number datatype to resolve this issue, either change your items inside array to plain number e.g. [10, 12, 18, ...] or use parseInt() function inside filter condition.

parseInt(ageabove, 10) >= 18

and yes, parseInt function is built-in inside javascript.

Then in ageResultAbove add join.

e.g.

console.log(`Voters under ${ageResultabove.join(", ")} category can vote`);

full code would be:

const ages = [10, 15, 18, 21, 24, 30, 32];

const ageResultabove = ages.filter((a) => a >= 18);
const ageResultbelow = ages.filter((a) => a < 18);

console.log(`Voters under ${ageResultabove.join(", ")} category can vote`);
console.log(`Voters under ${ageResultbelow.join(", ")} category cannot vote`);
Labham Jain
  • 308
  • 3
  • 8
  • _“This is because”_ — What is because what? What do you think the “problem” is? The question is how to rewrite the code more efficiently. The code works fine as is. Please use `parseInt` [_with_ the second parameter, `10`](/q/16880327/4642212). Consider using [`Number`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number#Function_syntax) or [`parseFloat`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseFloat) instead. `.join(", ")` doesn’t change anything. – Sebastian Simon Dec 11 '22 at 17:16
  • Thanks for the input, mybad I did'nt changed it earlier. – mohit_pamma Dec 11 '22 at 17:18
-3

Why don't you just concatenate the two strings? Like:

console.log(`Voters under ${ageResultabove} category can vote. Voters under ${ageResultbelow} category cannot vote`);

The && operator is used for logical comparison, therefore if you use it the result would be a boolean (True or False).

Fabrizio
  • 233
  • 1
  • 10