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

IF ELSE condition is always going to the ELSE

Here is my POST request:

router.post('/', (req, res) => {
    let body = { ...req.body };
    let odd = new Array();
    let even = new Array();
    let is_success = true;

    body.array.forEach((element) => {
        if (Number.isInteger(element)) {
            if (element % 2 == 0) {
                even.push(element);
            } else {
                odd.push(element);
            }
        } else {
            is_success = false;
            return;
        }
    });
    if (is_success) {
        res.status(200).json({
            is_success: `${is_success}`,
            user_id: 'john_doe_17091999',
            odd: `${odd}`,
            even: `${even}`,
        });
    } else
        res.status(200).json({
            is_success: `${is_success}`,
            user_id: 'john_doe_17091999',
        });
});

The condition is_success is not becoming true and that takes it to the else condition always. What I am trying to do is take the array and return odd and even arrays if all input elements are Integers:

{
"array": ["1", "2", "3"] 
}

Response:

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

{
"successful": true,
"odd": [1, 3],
"even": [2],
}

What it is always responding with:

{
    "is_success": "false",
    "user_id": "john_doe_17091999"
}

>Solution :

Your array contains strings. You need to convert them to numbers before you can run Number.isInteger() on them, otherwise it will always return ‘false’. You can do that by putting a ‘+’ before the element. See below.

Number.isInteger(+element)

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