3.10.1 Popcorn Hacks

// Create an array
let myArray = [1, 2, 3, 4, 5];

// Reverse the array
myArray.reverse();

// Output the reversed array
console.log(myArray);

// Create an empty array
let myArray = [];

// Add elements using unshift()
myArray.unshift(3); // [3]
myArray.unshift(2); // [2, 3]
myArray.unshift(1); // [1, 2, 3]

// Use the spread operator to add more elements
myArray = [0, ...myArray]; // [0, 1, 2, 3]

// Output the array
console.log(myArray);

// Original array
let numbers = [10, 25, 30, 47, 50, 65];

// Use filter() to create a new array with only even numbers
let evenNumbers = numbers.filter(num => num % 2 === 0);

// Output the new array
console.log(evenNumbers);

3.10.2 Popcorn Hacks

# Create a list
my_list = ['apple', 'banana', 'cherry']

# Use insert() method with a negative index
my_list.insert(-1, 'orange')  # Inserts 'orange' at the second-to-last position

# Output the updated list
print(my_list)

# First list
list1 = ['apple', 'banana', 'cherry']

# Second list
list2 = ['orange', 'pear', 'grape']

# Combine lists using the extend() method (popcorn hack)
list1.extend(list2)

# Output the combined list
print(list1)

# Create a list
my_list = ['apple', 'banana', 'cherry', 'orange', 'pear', 'grape']

# Method 1: Using remove() to remove an item by value
my_list.remove('banana')

# Method 2: Using pop() to remove an item by index (let's remove the last item)
my_list.pop()  # Removes 'grape'

# Method 3: Using del to remove an item by index (let's remove the first item)
del my_list[0]  # Removes 'apple'

# Output the updated list
print(my_list)

3.10.3 Main Hacks

# Step 1: Create an empty list to store grocery items
grocery_list = []

# Step 2: Input three grocery items and add them to the list
for i in range(3):
    item = input(f"Enter grocery item {i + 1}: ")
    grocery_list.append(item)

# Step 3: Display the current grocery list
print("\nCurrent Grocery List:", grocery_list)

# Step 4: Sort the list alphabetically and print the sorted list
grocery_list.sort()
print("\nSorted Grocery List:", grocery_list)

# Step 5: Remove one item specified by the user
item_to_remove = input("\nEnter an item to remove from the list: ")
if item_to_remove in grocery_list:
    grocery_list.remove(item_to_remove)
    print("\nUpdated Grocery List:", grocery_list)
else:
    print(f"\n'{item_to_remove}' is not in the grocery list.")

# Step 1: Create a list of integers from 1 to 20
original_list = list(range(1, 21))

# Step 2: Print the original list
print("Original List:", original_list)

# Step 3: Create a new list that contains only the even numbers using list comprehension
even_numbers = [num for num in original_list if num % 2 == 0]

# Step 4: Print the list of even numbers
print("Even Numbers:", even_numbers)

# Step 1: Create an empty list to store student grades
grades = []

# Step 2: Input three grades (as integers) and add them to the list
for i in range(3):
    while True:  # Loop until a valid integer is entered
        try:
            grade = int(input(f"Enter grade {i + 1}: "))
            grades.append(grade)
            break  # Exit the loop if input is valid
        except ValueError:  # Handle invalid input
            print("Please enter a valid integer.")

# Step 3: Print the list of grades after all grades are entered
print("\nList of Grades:", grades)

# Step 4: Create a new list that contains only grades above 60
passing_grades = [grade for grade in grades if grade > 60]

# Print this list
print("Grades above 60:", passing_grades)

# Step 1: Create a list of numbers from 1 to 10 (integers)
numbers = list(range(1, 11))

# Step 2: Print the original list
print("Original List:", numbers)

# Step 3: Sort the list in descending order
numbers.sort(reverse=True)
print("Sorted in Descending Order:", numbers)

# Step 4: Slice the list to get the first five numbers and print them
first_five = numbers[:5]
print("First Five Numbers:", first_five)

# Step 5: Sort the list again in ascending order and print it
numbers.sort()
print("Sorted in Ascending Order:", numbers)

3.10.4 Main Hacks

// Step 1: Create an array with at least 5 values
let myArray = ['apple', 'banana', 'cherry', 'date', 'fig'];

// Step 2: Display the array using console.log()
console.log("Original Array:", myArray);

// Bonus: Use the reverse() popcorn hack to reverse the array
myArray = [...myArray].reverse(); // Create a copy and reverse it

// Display the reversed array
console.log("Reversed Array:", myArray);

// Given array
const sports = ["soccer", "football", "basketball", "wrestling", "swimming"];

// Display values "soccer" and "wrestling" using their indexes
console.log("First sport:", sports[0]); // Accessing 'soccer'
console.log("Fourth sport:", sports[3]); // Accessing 'wrestling'

// Create an array called choresList initialized with four items
let choresList = ["laundry", "dishes", "vacuuming", "grocery shopping"];

// Display the initial list
console.log("Initial chores list:", choresList);

// Using push() to add an item
choresList.push("dusting");
console.log("After push:", choresList);

// Using shift() to remove the first item
choresList.shift();
console.log("After shift:", choresList);

// Using pop() to remove the last item
choresList.pop();
console.log("After pop:", choresList);

// Using unshift() to add an item to the beginning
choresList.unshift("clean windows");
console.log("After unshift:", choresList);

// Bonus: Use the push() and spread operator popcorn hack to add multiple values
choresList.push(...["mopping", "organizing", "watering plants"]);
console.log("After pushing multiple values:", choresList);

// Step 1: Create an array with ten random numbers (both even and odd)
const randomNumbers = [12, 7, 19, 24, 33, 8, 5, 10, 21, 40];

// Step 2: Function to count even numbers in the array
function countEvenNumbers(arr) {
    let count = 0; // Initialize count to zero
    for (let num of arr) {
        if (num % 2 === 0) { // Check if the number is even
            count++; // Increment the count if the number is even
        }
    }
    return count; // Return the final count
}

// Step 3: Call the function and display the output
const evenCount = countEvenNumbers(randomNumbers);
console.log("Count of even numbers:", evenCount);