Week 4 - Data structures and loops

Arrays

Loops

Objects

Package managers

Tools (IDE code editing)

Style - Autoformatting

Practice

Assignment

Back to core program

Content

Let’s get practical

Exercise 1: Array Manipulation - Shopping Cart

Build a shopping cart system using array methods.

Requirements:

  1. Create an array of product names: ['laptop', 'mouse', 'keyboard', 'monitor']
  2. Add 'headphones' to the cart using push()
  3. Remove the last item using pop()
  4. Check if 'mouse' is in the cart using includes()
  5. Find the position of 'keyboard' using indexOf()
  6. Create a new array with the first 2 items using slice()
  7. Log each step to see the results

Bonus: Create a second array of prices that corresponds to each product. Calculate the total price of items in the cart.

Exercise 2: Array Search - Find the Outlier

Given an array of numbers, find and remove specific values.

Requirements:

  1. Start with: [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
  2. Find the index of the first number greater than 30 (you'll need a loop for this)
  3. Use slice() to create a new array containing only numbers less than 25
  4. Check if the array includes the number 100
  5. Get the last 3 numbers using slice() with negative indices

Challenge: Create a function that takes an array and a target number, and returns true if the target exists, false otherwise. Don't use includes() - implement it yourself with a loop.

Exercise 3: The Collatz Conjecture

The Collatz conjecture is a famous unsolved problem in mathematics. The rules are simple:

Example: 10 → 5 → 16 → 8 → 4 → 2 → 1 (6 steps)

Requirements:

  1. Write a while loop that performs the Collatz sequence starting from any number
  2. Count how many steps it takes to reach 1
  3. Log each number in the sequence
  4. Test with starting number 27

Challenge: Find the first number under 100 that takes exactly 20 steps to reach 1. Use a for loop to test numbers 1-100.

Learn more:

Exercise 4: Object Restaurant Menu

Create a restaurant menu system using objects and loops.

Requirements:

  1. Create an object representing a menu item with properties: name, price, category, vegetarian
  2. Create an array of at least 5 menu items (different dishes)
  3. Use a for...of loop to print all menu items
  4. Use a for...of loop to calculate the total price if you ordered everything
  5. Use Object.keys() to list all properties of one menu item
  6. Create a new object using the spread operator that copies a menu item but changes the price

Bonus: Use destructuring to extract name and price from a menu item in a single line.

Challenge: Write a function that takes the menu array and returns only vegetarian items. Use a loop and push() to build the filtered array.


The HackYourFuture curriculum is licensed under CC BY-NC-SA 4.0 **

CC BY-NC-SA 4.0 Icons

*https://hackyourfuture.net/*