Stage 2: Frontend Fundamentals

JavaScript · Lesson 04

Arrays

map, filter, find and forEach — the methods used in everyday data work.

JavaScript3 min readFree lesson

Learning Goals

  • Create arrays and access elements by index.
  • Modify arrays with push, pop, shift, unshift, and splice.
  • Work with arrays using forEach, map, filter, find, includes, and sort.
  • Copy or merge arrays with the spread operator (...).

1. Creating and Accessing Arrays

// Create with an array literal
const fruits = ["apple", "banana", "strawberry", "grape"];

// Index access (starts at 0)
console.log(fruits[0]); // "apple"
console.log(fruits[2]); // "strawberry"

// Last element
console.log(fruits[fruits.length - 1]); // "grape"

// Mixing different types is allowed
const mixed = [1, "hello", true, null, { name: "John Doe" }];

2. Array Mutation Methods

const arr = ["A", "B", "C"];

// push: add to the end → returns the new length
arr.push("D");        // ["A", "B", "C", "D"]

// pop: remove from the end → returns the removed element
const last = arr.pop(); // last = "D", arr = ["A", "B", "C"]

// unshift: add to the front → returns the new length
arr.unshift("Z");     // ["Z", "A", "B", "C"]

// shift: remove from the front → returns the removed element
const first = arr.shift(); // first = "Z", arr = ["A", "B", "C"]

// splice(startIndex, deleteCount, ...itemsToAdd)
arr.splice(1, 1);           // ["A", "C"] (remove 1 item at index 1)
arr.splice(1, 0, "B");      // ["A", "B", "C"] (insert "B" at index 1)
arr.splice(1, 1, "X", "Y"); // ["A", "X", "Y", "C"] (replace)

3. Higher-Order Functions

These are powerful methods that apply a function to each element of an array.

forEach — perform an action on each element (no return value)

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

numbers.forEach((num, index) => {
  console.log(`item ${index}: ${num}`);
});

map — return a new array with each element transformed

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

const names = ["alice", "bob", "charlie"];
const capitalized = names.map(name => name.toUpperCase());
// ["ALICE", "BOB", "CHARLIE"]

filter — return a new array with only the elements that match a condition

const numbers = [1, 2, 3, 4, 5, 6, 7, 8];
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4, 6, 8]

const users = [
  { name: "John Doe", age: 25 },
  { name: "Susan Lee", age: 15 },
  { name: "Michael Grant", age: 30 },
];
const adults = users.filter(user => user.age >= 19);
// [{ name: "John Doe", age: 25 }, { name: "Michael Grant", age: 30 }]

find — return the first element that matches a condition

const users = [
  { id: 1, name: "John Doe" },
  { id: 2, name: "Susan Lee" },
];
const user = users.find(u => u.id === 2);
console.log(user); // { id: 2, name: "Susan Lee" }

includes — check whether a specific value is present

const fruits = ["apple", "banana", "strawberry"];
console.log(fruits.includes("banana")); // true
console.log(fruits.includes("watermelon"));  // false

sort — sort an array (mutates the original array)

// String sorting (default: alphabetical)
const names = ["Charlie", "Alice", "Bob"];
names.sort();
console.log(names); // ["Alice", "Bob", "Charlie"]

// Number sorting (always provide a comparison function!)
const numbers = [10, 1, 100, 3, 20];
numbers.sort((a, b) => a - b);  // ascending
console.log(numbers); // [1, 3, 10, 20, 100]

numbers.sort((a, b) => b - a);  // descending
console.log(numbers); // [100, 20, 10, 3, 1]

4. Spread Operator

// Copy an array (independent of the original)
const original = [1, 2, 3];
const copy = [...original];
copy.push(4);
console.log(original); // [1, 2, 3] (unaffected)

// Merge arrays
const a = [1, 2, 3];
const b = [4, 5, 6];
const merged = [...a, ...b]; // [1, 2, 3, 4, 5, 6]

// Add elements to an array
const withExtra = [0, ...a, 4]; // [0, 1, 2, 3, 4]

Practice Files

  • Example
  • Assignment
  • Assignment Solution

Assignment

Assignment 04 — Movie Favorites

Assignment Goal

Build a movie favorites app using array methods (push, filter, map, includes).


Requirements

Features

  1. Add a movie: type a movie title and click the "Add" button to add it to the list
  2. Search: typing in the search box filters the list in real time to show only movies whose titles contain the search term
  3. Delete: delete individual movies with the delete button on each movie item
  4. Clear all: clear the entire list when the button is clicked

Initial Data

When the app starts, the following movies must be in the list:

const movies = [
  "Interstellar",
  "Parasite",
  "Avengers: Endgame",
  "Titanic",
  "La La Land"
];

Additional Conditions

  • If the same movie title already exists, show the message "This movie has already been added." (use includes)
  • Empty titles are not added.
  • If the search box is empty, show the full list.
  • Search works case-insensitively. (use .toLowerCase())
  • Use map to render the list.
  • Use filter to implement search and deletion.

Hints

// Duplicate check (includes)
if (movies.includes(newTitle)) { /* handle the duplicate */ }

// Search filter (filter + includes + toLowerCase)
const filtered = movies.filter(m => 
  m.toLowerCase().includes(searchTerm.toLowerCase())
);

// List rendering (map + join)
const html = filtered.map((movie, index) => `
  <li>${movie} <button onclick="deleteMovie(${index})">Delete</button></li>
`).join('');

File Structure

assignment/
└── index.html   ← write your code here

Grading Criteria

Item Points
Add movie feature (push, duplicate check) 25 points
Real-time search feature (filter + includes) 25 points
Individual delete feature (filter) 20 points
List rendering with map 20 points
UI structure and empty state handling 10 points

100 points total

Learn this lesson with a mentor

Work through the Build Your Homepage series on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now