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:
{
"successful": true,
"odd": [1, 3],
"even": [2],
}
What it is always responding with:
{
"is_success": "false",
"user_id": "john_doe_17091999"
}
CodePudding user response:
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)
CodePudding user response:
You must cast every element to Number before using the Number.isInteger otherwise you'll get false.
Example: Number.isInteger("2") will return false Number.isInteger(Number("2")) will return true