Home > Net >  create a function findItems
create a function findItems

Time:05-26

I have been learning Javascript for a few weeks now(mostly just arrays, functions, for loops and if statements). I have come across a problem that has stumped me and would greatly appreciate any kind of insight or breakdown of the problem.

Here is the problem:

Create a function findItems that
•   takes in two arguments: an array of items, and a type of item as a string
•   returns an array of items that have a type that matches the type passed in

Using the example data below, findItems(items, "book") /* =>

[{ 
    itemName: "Effective Programming Habits", 
    type: "book", 
    price: 18.99
}]
  */

Note: after you write this function and the first set of tests pass, a second set of tests will show up for part 2. Part 2 - Find Items, Extended

Add the following features to your findItems function:
    •   If there are no items in the cart array, return the string "Your cart does not have any items in it."
    •   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.".
Sample Shopping Cart Data

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
  }
];

Would anyone know how to solve this? Or be able to offer a breakdown of it?

CodePudding user response:

You should loop over the given array, then add any objects with the type field to a temporary array, then return the array. Something like this:

function findItems(arr, type) {
    let temp = [];
    for (let i = 0; i < arr.length; i  ) {
        const item = arr[i];
        if (item.type === type) {
            temp.push(item);
        }
    }
    return temp;
}
  • Related