First of all this does not work for me, And I explain it so that they do not close the question, I am making two more or less equal algorithms with ternary conditional, simply one is an array of objects and the other an array of numbers, and with the numbers I don't have that problem, that's why What do I think is a problem with the code: When should I use a return statement in ES6 arrow functions
I'm new to the world of javascript and when doing a reduce for an array, I want to try to count the number of times the age is equal in an array of objects whose properties are the ages.
However when I do a ternary conditional I receive that the output is undefined.
but when doing a normal if with an else if you can do the count: Code: const numbers = [ {age: 4, age2: 4}, {age: 5, age2: 6}, {age: 88, age2: 99}, {age:14, age2:14}, {age: 2, age2: 2} ];
const getCount = ( objects ) => objects.reduce((acc, el) => {
if ( el.age === el.age2 ) {
return acc += 1;
}
else {
return acc;
}
}, 0);
const b = getCount(numbers)
console.log(b)
Output:
3
But with this Code:
const numbers = [ {age: 4, age2: 4}, {age: 5, age2: 6}, {age: 88, age2: 99}, {age:14, age2:14}, {age: 2, age2: 2} ];
const getCount = ( objects ) => objects.reduce((acc, el) => {
el.age === el.age2 ? acc += 1 : acc;
}, 0);
const b = getCount(numbers)
console.log(b)
Output
undefined
However, if I don't use objects and I only do the count if some element is repeated, with the same ternary conditional, this does work.
const count2 = ( objects ) => objects.reduce( (acc, el) => el === 1 ? acc += 1 : acc )
console.log(count2( [0, 1, 2, 3, 4, 5, 1, 1, 4] ))
Output
3
Please I do not understand what happens, what is the error