← Back to Course Overview

Module 3: Manipulating Arrays

In this module, we'll explore advanced array manipulation techniques in JavaScript. Arrays are powerful data structures, and JavaScript provides many built-in methods to add, remove, find, and transform array elements efficiently.

Array Methods for Adding and Removing Elements

JavaScript provides several methods for adding elements to and removing elements from arrays. These methods modify the original array and can be very useful for managing collections of data.

Adding Elements with push()

The push() method adds one or more elements to the end of an array and returns the new length of the array:

const fruits = ['Apple', 'Banana'];

// Add a single element
const newLength = fruits.push('Cherry');
console.log(fruits); // ['Apple', 'Banana', 'Cherry']
console.log(newLength); // 3 (new length of the array)

// Add multiple elements
fruits.push('Date', 'Elderberry');
console.log(fruits); // ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry']

Other Methods for Adding Elements

  • unshift(): Adds elements to the beginning of an array
  • splice(): Can add elements at any position in an array

Removing Elements with pop()

The pop() method removes the last element from an array and returns that element:

const fruits = ['Apple', 'Banana', 'Cherry'];

const removedItem = fruits.pop();
console.log(fruits); // ['Apple', 'Banana']
console.log(removedItem); // 'Cherry'

Common Use Cases

  • Implementing stacks (LIFO - Last In, First Out) with push() and pop()
  • Implementing queues (FIFO - First In, First Out) with push() and shift()
  • Managing task lists or user collections
  • Building dynamic UI components that need to add or remove items

Array Methods for Adding and Removing Elements (curated content)

Finding Information in Arrays

When working with arrays, we often need to find specific elements or obtain portions of arrays. JavaScript provides several methods to help with these tasks.

Finding Elements with indexOf()

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it's not present:

const fruits = ['Apple', 'Banana', 'Cherry', 'Apple'];

const index = fruits.indexOf('Cherry');
console.log(index); // 2

const notFound = fruits.indexOf('Mango');
console.log(notFound); // -1

// Find 'Apple' starting from index 1 (skipping the first 'Apple')
const secondApple = fruits.indexOf('Apple', 1);
console.log(secondApple); // 3

Getting Subarrays with slice()

The slice() method returns a shallow copy of a portion of an array into a new array without modifying the original array:

const fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];

// Get elements from index 1 to 3 (exclusive)
const citrus = fruits.slice(1, 3);
console.log(citrus); // ['Banana', 'Cherry']

// Get elements from index 2 to the end
const lastThree = fruits.slice(2);
console.log(lastThree); // ['Cherry', 'Date', 'Elderberry']

// Using negative indices (counts from the end)
const lastTwo = fruits.slice(-2);
console.log(lastTwo); // ['Date', 'Elderberry']

slice() vs splice()

It's important to understand the difference between these similarly named methods:

  • slice() does not modify the original array and returns a new array
  • splice() modifies the original array by removing, replacing, or adding elements

Finding Information in Arrays (curated content)

Callback-Based Array Methods

Modern JavaScript provides powerful array methods that accept callback functions, allowing for more expressive and concise code when transforming or processing arrays.

What is a Callback Function?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of action. In the context of array methods, callbacks are used to process each element of the array.

// A simple callback function
function processItem(item) {
  return item.toUpperCase();
}

// Using the callback with an array method
const fruits = ['apple', 'banana', 'cherry'];
const uppercaseFruits = fruits.map(processItem);
console.log(uppercaseFruits); // ['APPLE', 'BANANA', 'CHERRY']

Using forEach()

The forEach() method executes a provided function once for each array element, but doesn't return a value:

const numbers = [1, 2, 3, 4, 5];
let sum = 0;

numbers.forEach(function(number) {
  sum += number;
});

console.log(sum); // 15

// With arrow function syntax
const fruits = ['Apple', 'Banana', 'Cherry'];
fruits.forEach(fruit => {
  console.log(`I like ${fruit}s`);
});
// Outputs:
// I like Apples
// I like Bananas
// I like Cherrys

Using map()

The map() method creates a new array with the results of calling a function on every element in the calling array:

const numbers = [1, 2, 3, 4, 5];

// Create a new array with each number doubled
const doubled = numbers.map(function(number) {
  return number * 2;
});

console.log(doubled); // [2, 4, 6, 8, 10]
console.log(numbers); // [1, 2, 3, 4, 5] - original array unchanged

// With arrow function syntax
const squared = numbers.map(num => num * num);
console.log(squared); // [1, 4, 9, 16, 25]

Using filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Filter for even numbers
const evenNumbers = numbers.filter(function(number) {
  return number % 2 === 0;
});

console.log(evenNumbers); // [2, 4, 6, 8, 10]

// With arrow function syntax - filter for numbers greater than 5
const largeNumbers = numbers.filter(num => num > 5);
console.log(largeNumbers); // [6, 7, 8, 9, 10]

When to Use Each Method

  • forEach(): When you want to execute code for each element without creating a new array
  • map(): When you want to transform each element in an array and create a new array with the results
  • filter(): When you want to select a subset of elements that meet certain criteria

Callback-Based Array Methods (curated content)

Guided Project

In this guided project, you'll apply your knowledge of array manipulation to solve practical problems. You'll work with the array methods you've learned to process, transform, and analyze collections of data.

Project Objectives

  • Practice using push(), pop(), and other array modification methods
  • Implement indexOf() and slice() to search and extract data from arrays
  • Use callback-based methods like forEach(), map(), and filter() to process data
  • Combine multiple array methods to solve more complex problems
  • Apply array manipulation techniques in a real-world context

Follow along with the video to complete the guided project. The instructor will demonstrate how to use array methods effectively to solve different types of problems.

Additional Resources

Looping Over Data Structures

Working with objects and arrays often requires processing multiple values. Loops allow you to perform operations on each item in a collection, saving you from writing repetitive code.

Basic Looping Concepts

JavaScript provides several ways to loop through data structures. The most common approaches are:

Common Loop Types

  • for loops: Traditional loops with initialization, condition, and increment steps
  • while loops: Conditional loops that continue as long as a condition is true
  • for...of loops: Modern syntax for iterating over array elements
  • for...in loops: Used for iterating over object properties

Looping Over Array Indices

The classic for loop is often used to iterate through arrays using their indices:

const fruits = ['Apple', 'Banana', 'Cherry'];

// Loop through the array
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
// Outputs:
// Apple
// Banana
// Cherry