I'm having trouble getting my function to work properly. Depending upon the conditions, I want my function to return a new array by pushing into the new array. If the if conditions are false, I want to return two different string messages. Here is an example of my dataset:
let items = [
{
itemName: "Effective Programming Habits",
type: "book",
price: 18.99
},
{
itemName: "Creation 3005",
type: "computer",
price: 399.99
},
{
itemName: "Orangebook Pro",
type: "computer",
price: 899.99
}
So far, when my function takes in an array of items and a type of item as the string search word, it is returning an array of items that have a type that matches the type passed through the function. However, I also want my function to return two other things.
If there are no items in the cart array, return the string "Your cart does not have any items in it." Wouldn't this be written as matches.length === 0
? If there are no items that match the given type, return the string "No items found of that type. Please search for a different item.". Wouldn't this be written as if (search != items[i].type)
?
How would I get these two strings to also return given the conditions? I feel as If I'm getting tripped up on the order in which these statements are being executed. Here is my code so far without the two string return values.
function findItems (items, search) {
let matches = [];
for (i = 0; i < items.length; i++) {
if (items[i].type.includes(search)) {
matches.push(items[i])
}
}
return matches;
}
In sum, I want the function to return an array if a search matches. If the first condition is false, I want to return one of two other string messages based on new conditions.
Aucun commentaire:
Enregistrer un commentaire