Issue
I have an array with elements and I want to compare the URL input to it.
For example when a user inputs localhost:8080/ingredients/raisins
I want to return In Stock
and if it’s something that’s not inside the array (eg. /ingredients/chicken
), it should be Out of Stock
.
However, for the time being it just returns Out of Stock
, no matter the user’s input. What am I missing here?
const express = require("express");
const app = express();
const ingredients = ["Raisins", "Pepper", "Beef"];
app.get("/ingredients/:ingredient", (req, res) => {
const { ingredient } = req.params;
const foundIngredient = ingredients.find((item) => item === ingredient);
if (foundIngredient) {
res.send("In Stock!");
} else {
res.send("Out of Stock!");
}
});
app.listen(8080, () => {
console.log("I am running on port 8080");
});
Solution
Looks like you have some error on the capitalize word , try to standardize the word before comparing. You can try to compare all with lower case .
Or as @Joel said you can use "localCompare" this to better performance comparing
const foundIngredient = ingredients.some((item) =>item.localeCompare(ingredient, "en", { sensitivity: "base" }));
if (foundIngredient) {
res.send("In Stock!");
} else {
res.send("Out of Stock!");
}
And also as improve not use find()
, because you are looking for a boolean, not a entity,so you can use some()
instead, take a look here how to use it
Answered By – eborrallo
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0