Module 11 : Arrays and Array Methods
1. Introduction to Arrays in JavaScript
Definition:
An Array is a special variable that can hold more than one value at a time. It is one of the most essential data structures in JavaScript and is used to store a list of elements (numbers, strings, objects, etc.).
Syntax:
javascript
code
let fruits = ["Apple", "Banana", "Cherry"];
Key Characteristics:
Arrays are zero-indexed (the first element is at index 0).
Arrays can store multiple types of data.
Arrays are mutable, meaning you can change their contents.
2. Creating Arrays
Using Array Literals:
javascript
code
let colors = ["Red", "Green", "Blue"];
Using the Array Constructor:
javascript
code
let scores = new Array(100, 90, 80);
Note: Prefer using array literals for readability and simplicity.
3. Accessing and Modifying Elements
Accessing:
javascript
code
let fruits = ["Apple", "Banana", "Cherry"]; console.log(fruits[0]); // Apple
Modifying:
javascript
code
fruits[1] = "Mango"; console.log(fruits); // ["Apple", "Mango", "Cherry"]
4. Common Array Properties
Property
Description
Example
length
Returns the number of items
fruits.length → 3
5. Essential Array Methods with Examples
1. push()
Adds elements to the end of an array.
javascript
code
let nums = [1, 2]; nums.push(3); // [1, 2, 3]
2. pop()
Removes the last element.
javascript
code
nums.pop(); // [1, 2]
3. unshift()
Adds elements to the beginning.
javascript
code
nums.unshift(0); // [0, 1, 2]
4. shift()
Removes the first element.
javascript
code
nums.shift(); // [1, 2]
5. indexOf()
Returns the first index of a specified value.
javascript
code
nums.indexOf(2); // 1
6. includes()
Checks if an element exists.
javascript
code
nums.includes(2); // true
7. slice()
Extracts a section of an array.
javascript
code
let colors = ["red", "green", "blue", "yellow"]; let part = colors.slice(1, 3); // ["green", "blue"]
8. splice()
Adds/removes elements at a specific index.
javascript
code
colors.splice(2, 1, "purple"); // Removes 1 at index 2, adds "purple"
9. forEach()
Executes a function for each item.
javascript
code
colors.forEach(color => console.log(color));
10. map()
Creates a new array by applying a function to each item.
javascript
code
let numbers = [1, 2, 3]; let squared = numbers.map(n => n * n); // [1, 4, 9]
11. filter()
Creates a new array with elements that pass a condition.
javascript
code
let even = numbers.filter(n => n % 2 === 0); // [2]
12. reduce()
Reduces the array to a single value.
javascript
code
let total = numbers.reduce((sum, n) => sum + n, 0); // 6
6. Advanced Usage & Examples
Example 1: Removing Duplicates
javascript
code
let items = [1, 2, 2, 3, 4, 4]; let uniqueItems = [...new Set(items)]; console.log(uniqueItems); // [1, 2, 3, 4]
Example 2: Capitalizing Array of Strings
javascript
code
let names = ["alice", "bob"]; let capNames = names.map(name => name.charAt(0).toUpperCase() + name.slice(1));
7. Movie Rating Manager
Objective:
To use various array methods to manage a movie rating system.
Instructions:
Create an array movies with objects containing title, genre, and rating.
Filter out movies with rating < 8.
Create a new array of movie titles only.
Add a new movie.
Remove a movie by title.
Display all movies in formatted strings.
Code Implementation:
javascript
code
let movies = [ { title: "Inception", genre: "Sci-Fi", rating: 9 }, { title: "Avatar", genre: "Fantasy", rating: 7.5 }, { title: "Joker", genre: "Drama", rating: 8.5 } ]; // Filter let topRated = movies.filter(m => m.rating >= 8); // Map titles let titles = movies.map(m => m.title); // Add new movie movies.push({ title: "Tenet", genre: "Action", rating: 8 }); // Remove a movie movies = movies.filter(m => m.title !== "Avatar"); // Display movies.forEach(m => { console.log(`${m.title} (${m.genre}) - Rating: ${m.rating}`); });
Expected Output:
yaml
code
Inception (Sci-Fi) - Rating: 9
Joker (Drama) - Rating: 8.5
Tenet (Action) - Rating: 8
8. Exercises
Exercise 1:
Write a function that returns the sum of all even numbers in an array.
Hint: Use filter() and reduce().
Exercise 2:
Create a function that accepts an array of strings and returns a new array with strings reversed.
Hint: Use map() and split().reverse().join().
Exercise 3:
Sort an array of numbers in descending order.
9. The Performance of Array Methods
Brief:
When dealing with large data sets, array methods like map, filter, and reduce may introduce performance overhead compared to traditional for loops.
Activity:
Measure the execution time of filtering an array of 1 million elements using filter() vs. for loop.
Analyze and compare performance.
javascript
code
let largeArray = Array.from({ length: 1000000 }, (_, i) => i); console.time("filter"); let evens = largeArray.filter(n => n % 2 === 0); console.timeEnd("filter"); console.time("for loop"); let evens2 = []; for (let i = 0; i < largeArray.length; i++) { if (largeArray[i] % 2 === 0) evens2.push(largeArray[i]); } console.timeEnd("for loop");
Expected Result: The for loop is usually faster, especially for large arrays.
10. Summary
Arrays are fundamental to organizing and manipulating collections of data in JavaScript.
Understanding both basic and advanced array methods is crucial.
Each method has a specific use case and improves code readability and efficiency.
Hands-on practice and performance profiling are essential to master their usage.
No comments:
Post a Comment