15.3 Advanced Array Methods (15 mins)

  1. Introduction to Advanced Array Methods: JavaScript provides powerful methods for manipulating arrays. These methods allow you to extract portions of arrays, insert or remove elements, search for elements, and iterate over arrays.

  2. Array Methods:

    • slice(): Returns a shallow copy of a portion of an array into a new array, without modifying the original array. You provide the start and (optional) end index.

  • Syntax: array.slice(start, end)

  • Example:

    let fruits = ["Apple", "Banana", "Orange", "Mango", "Pineapple"];
    let slicedFruits = fruits.slice(1, 3);
    console.log(slicedFruits);  // Outputs: ["Banana", "Orange"] (extracted from index 1 to index 3, excluding 3)
    console.log(fruits);  // Original array remains unchanged
  • splice(): Changes the contents of an array by removing, replacing, or adding elements. It modifies the original array.

  • Syntax: array.splice(start, deleteCount, item1, item2, ...)

  • Example (Remove and Add Elements):

    let fruits = ["Apple", "Banana", "Orange"];
    fruits.splice(1, 1, "Grapes", "Peach");
    console.log(fruits);  // Outputs: ["Apple", "Grapes", "Peach", "Orange"] (Banana is replaced)
  • indexOf(): Returns the first index at which a specified element is found in the array. Returns -1 if the element is not found.

    • Syntax: array.indexOf(element)

    • Example:

      let fruits = ["Apple", "Banana", "Orange"];
      console.log(fruits.indexOf("Banana"));  // Outputs: 1 (index of "Banana")
      console.log(fruits.indexOf("Grapes"));  // Outputs: -1 (not found)
  • forEach(): Executes a provided function once for each array element. It's useful for iterating over arrays.

    • Syntax: array.forEach(function(element, index, array))

    • Example:

      let fruits = ["Apple", "Banana", "Orange"];
      fruits.forEach(function(fruit, index) {
        console.log(index + ": " + fruit);
      });
      // Outputs: 0: Apple, 1: Banana, 2: Orange

Student Activity (15 mins):

Objective: Students will practice using advanced array methods to extract, modify, find, and iterate over arrays.


Step-by-Step Activity:

  1. Create an HTML file (e.g., arrays_advanced_methods.html) and write JavaScript code that demonstrates the use of advanced array methods.

  2. Example Code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Advanced Array Methods</title>
    </head>
    <body>
      <h1>Check the Console for Advanced Array Method Outputs</h1>
    
      <script>
        // 1. slice(): Extract a portion of an array
        let colors = ["Red", "Green", "Blue", "Yellow", "Purple"];
        let slicedColors = colors.slice(1, 4);  // Extracts Green, Blue, and Yellow
        console.log("Sliced Colors: " + slicedColors);  // Outputs: Green, Blue, Yellow
        console.log("Original Colors: " + colors);  // Original array remains unchanged
    
        // 2. splice(): Remove and add elements to an array
        colors.splice(2, 1, "Orange", "Pink");  // Replaces "Blue" with "Orange" and "Pink"
        console.log("Colors after splice: " + colors);  // Outputs: Red, Green, Orange, Pink, Yellow, Purple
    
        // 3. indexOf(): Find the index of an element
        let indexOfYellow = colors.indexOf("Yellow");
        console.log("Index of Yellow: " + indexOfYellow);  // Outputs: 4
    
        let indexOfBlack = colors.indexOf("Black");
        console.log("Index of Black: " + indexOfBlack);  // Outputs: -1 (not found)
    
        // 4. forEach(): Iterate over the array
        colors.forEach(function(color, index) {
          console.log(index + ": " + color);
        });
        // Outputs:
        // 0: Red
        // 1: Green
        // 2: Orange
        // 3: Pink
        // 4: Yellow
        // 5: Purple
      </script>
    </body>
    </html>
  3. Run the file in a browser:

    • Open the HTML file in a browser and use Developer Tools (F12 or right-click and select Inspect > Console) to view the results of the array methods.

  4. Activity:

    • Step 1: Use slice() to extract the first 3 elements from an array and print the result.

      let numbers = [10, 20, 30, 40, 50];
      let slicedNumbers = numbers.slice(0, 3);  // Extracts [10, 20, 30]
      console.log("Sliced Numbers: " + slicedNumbers);
    • Step 2: Use splice() to replace an element in an array with two new elements.

      let animals = ["Cat", "Dog", "Elephant"];
      animals.splice(1, 1, "Rabbit", "Lion");  // Replaces "Dog" with "Rabbit" and "Lion"
      console.log("Updated Animals: " + animals);  // Outputs: ["Cat", "Rabbit", "Lion", "Elephant"]
    • Step 3: Use indexOf() to find the position of a specific element in an array.

      let fruits = ["Apple", "Banana", "Cherry"];
      console.log("Index of Banana: " + fruits.indexOf("Banana"));  // Outputs: 1
    • Step 4: Use forEach() to iterate through an array and print each element and its index.

      let cities = ["New York", "Los Angeles", "Chicago"];
      cities.forEach(function(city, index) {
        console.log(index + ": " + city);  // Outputs index and city name
      });

  5. Challenge:

modify the code to show the results in a <div id="Result"> in index.html and add a "Next" button to carry out the step-by-step processing of the `console.log` outputs, you can follow these steps:

  1. Add a <div> element with the id "Result" to display the results.

  2. Add a "Next" button to trigger the display of each step.

  3. Modify the JavaScript to handle the button click and display each result sequentially.

Here's the modified code:

// Challenege  code
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Advanced Array Methods</title>
    <style>
      #Result {
        margin-top: 20px;
        padding: 10px;
        border: 1px solid #ccc;
      }
    </style>
  </head>
  <body>
    <h1>Advanced Array Method Outputs</h1>
    <div id="Result">Click "Next" to see the results.</div>
    <button id="nextButton">Next</button>

    <script>
      let colors = ["Red", "Green", "Blue", "Yellow", "Purple"];
      let slicedColors = colors.slice(1, 4);
      let indexOfYellow = colors.indexOf("Yellow");
      let indexOfBlack = colors.indexOf("Black");

      let results = [
        "Sliced Colors: " + slicedColors,
        "Original Colors: " + colors,
        "Colors after splice: " + colors.splice(2, 1, "Orange", "Pink") ||
          colors,
        "Index of Yellow: " + indexOfYellow,
        "Index of Black: " + indexOfBlack,
      ];

      colors.forEach(function (color, index) {
        results.push(index + ": " + color);
      });

      let currentIndex = 0;
      const resultDiv = document.getElementById("Result");
      const nextButton = document.getElementById("nextButton");

      nextButton.addEventListener("click", function () {
        if (currentIndex < results.length) {
          resultDiv.innerHTML += "<br>" + results[currentIndex];
          currentIndex++;
        } else {
          resultDiv.innerHTML += "<br>All results displayed.";
          nextButton.disabled = true;
        }
      });
    </script>
  </body>
</html>
  • JavaScript Logic:

    • Created an array results to store all the output strings.

    • Used a currentIndex to keep track of which result to display next.

    • Added an event listener to the "Next" button to display the next result in the results array each time it's clicked.

    • Disabled the button once all results have been displayed.

  • Write a function that finds the first occurrence of a number greater than 10 in an array and returns its index using indexOf() and splice().

    let numbers = [5, 8, 12, 19, 3];
    let greaterThanTen = numbers.findIndex(num => num > 10);
    console.log("First number greater than 10 is at index: " + greaterThanTen);  // Outputs: 2

Activity Follow-up Questions:

  1. How does slice() differ from splice() when working with arrays?

  2. What advantage does forEach() offer over a traditional for loop when iterating over arrays?

  3. In what scenarios would you use indexOf() to search for elements in an array?


Expected Outcome:

Students will:

  • Understand how to use advanced array methods like slice(), splice(), indexOf(), and forEach().

  • Practice extracting and modifying elements in arrays using slice() and splice().

  • Learn how to search for elements in arrays using indexOf() and how to iterate over arrays using forEach().

Last updated