15.3 Advanced Array Methods (15 mins)
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.
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 unchangedsplice(): 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-1if 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:
Create an HTML file (e.g.,
arrays_advanced_methods.html) and write JavaScript code that demonstrates the use of advanced array methods.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>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.
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: 1Step 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 });
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:
Add a
<div>element with theid"Result" to display the results.Add a "Next" button to trigger the display of each step.
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
resultsto store all the output strings.Used a
currentIndexto keep track of which result to display next.Added an event listener to the "Next" button to display the next result in the
resultsarray 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()andsplice().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:
How does
slice()differ fromsplice()when working with arrays?What advantage does
forEach()offer over a traditionalforloop when iterating over arrays?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(), andforEach().Practice extracting and modifying elements in arrays using
slice()andsplice().Learn how to search for elements in arrays using
indexOf()and how to iterate over arrays usingforEach().
Last updated