So, I am new to JavaScript and I am having trouble with making a function work the way I want it to. As it stands, it prints the contents of "tomato" just fine and can tell if an item is not with in the list … sort of. If I enter "t-shirt" or "soap", it does not add its contents into the newArray variable and adds "Item not found" instead. So, it does not recognize anything past "tomato". Another issue is that it does not tell me if an array is not empty, so it never shows "No items found in cart", just an empty array. Here is what I have tried so far. Any help would be appreciated. Thank you.
let items =
[
{
name: "tomato",
type: "produce",
price: 0.99
},
{
name: "soap",
type: "cleaning",
price: 0.99
},
{
name: "t-shirt",
type: "clothing",
price: 5.99
}
]
function searchItem(items,string)
{
let newArray = [];
for (i=0;i<items.length;i++)
{
if (string === items[i].name)
{
newArray.push(items[i])
break
}
else if(string != items[i].name)
{
newArray.push("Item not found")
break
}
else
{
return "Item does not exist"
}
}
return newArray
}
searchItem(items,"tomato")
>Solution :
The problem is in the logic, you tried to evaluate your search result in the loop. that’s why as @cjmling suggested, if your search value does not match the first index, it will always result in item not found. So the soulution based on your description is like this:
let items =
[
{
name: "tomato",
type: "produce",
price: 0.99
},
{
name: "soap",
type: "cleaning",
price: 0.99
},
{
name: "t-shirt",
type: "clothing",
price: 5.99
}
]
function searchItem(items,string)
{
let newArray = [];
// if the cart is empty return this
if (items.length === 0) {
return "No items found in cart"
}
// if the cart is not empty run the loop
for (i=0;i<items.length;i++)
{
if (string === items[i].name)
{
newArray.push(items[i])
}
}
// if search result is 0, then return this
if (newArray.length === 0) {
return ["Item not found"]
} else {
return newArray
}
}
console.log(searchItem(items,"tomato"))
console.log(searchItem(items,"soap"))
console.log(searchItem([],"tomato"))
console.log(searchItem(items,"human"))