简体   繁体   中英

Ternary conditional works one time but not another javascript

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

You have forgotten to return the accumulator value:

const getCount = ( objects ) => objects.reduce((acc, el) => {
      return el.age === el.age2 ? acc += 1 : acc;
    }, 0);

You can also remove the { } and the keywork return

const getCount = ( objects ) => objects.reduce((acc, el) => el.age === el.age2 ? acc += 1 : acc, 0)

Beside the missing return statement and using a block statement, you could simplifiy the function and just add the accumulator and the comparison value.

const getCount = objects => objects.reduce((acc, el) => acc + (el.age === el.age2), 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM