Lesson 7
24 min
Create, traverse and manipulate arrays with push, map, filter...
Definition
An array is a data structure that stores anordered list of values in a single variable. Each value, called an element, is located by its position, the index, which starts at0. An array is created with square brackets:[value1, value2, value3].
An array is a data structure that lets you store anordered list of values in a single variable: a list of products, a list of grades, a list of users... Each value in the array is accessible through its position, called the index, which always starts at0.
const fruits = ["apple", "banana", "kiwi"];
console.log(fruits[0]); // "apple" (first element, index 0)
console.log(fruits[1]); // "banana"
console.log(fruits[2]); // "kiwi"
console.log(fruits[10]); // undefined (non-existent index)
console.log(fruits.length); // 3 (number of elements)Without arrays, you would have to create one variable per value (fruit1, fruit2, fruit3...), which would quickly become unmanageable. Instead, imagine a row ofnumbered lockers: the array is the entire row, each locker contains a value, and its number is the index. The first locker is number 0, not 1.
An array can be empty, contain numbers, text, booleans, or even mix several types. It can also contain other arrays, which makes it possible to represent a grid.
const empty = []; // empty array
const grades = [12, 15.5, 9, 18]; // numbers
const mixed = ["Léa", 28, true, null]; // mixed types (possible but not recommended)
const grid = [[1, 2, 3], [4, 5, 6]]; // an array of arrays
console.log(grid[1][2]); // 6 (row at index 1, column at index 2)
console.log(typeof grades); // "object" (an array is an object)
console.log(Array.isArray(grades)); // true (to check that it is an array)Since the index starts at 0, the last element of an array is at indexlength - 1. The at() method also lets you use a negative index to count from the end.
const days = ["monday", "tuesday", "wednesday", "thursday"];
console.log(days[days.length - 1]); // "thursday"
console.log(days.at(-1)); // "thursday" (shorter)
console.log(days.at(-2)); // "wednesday"
days[0] = "MONDAY"; // we modify the first element
console.log(days); // ["MONDAY", "tuesday", "wednesday", "thursday"]const and arrays
An array declared with const can still be modified (adding, removing, or changing an element). Whatconst forbids is reassigning the variable so that it points to a different array.
const fruits = ["apple", "banana"];
fruits.push("mango"); // adds to the end → ["apple", "banana", "mango"]
fruits.pop(); // removes the last element → ["apple", "banana"]
fruits.unshift("strawberry"); // adds to the start → ["strawberry", "apple", "banana"]
fruits.shift(); // removes the first element → ["apple", "banana"]
// Modify a specific element via its index:
fruits[0] = "pear"; // ["pear", "banana"]push / pop: add or remove an element at the end of the array.unshift / shift: add or remove an element at the start of the array.To act at a specific position,splice(index, deleteCount, ...itemsToAdd) deletes and/or inserts elements, modifying the array.slice(start, end), on the other hand, returns acopy of a portion of the array without changing anything (the end position is excluded).
const letters = ["a", "b", "c", "d", "e"];
// slice: extracts without modifying
console.log(letters.slice(1, 3)); // ["b", "c"]
console.log(letters); // ["a", "b", "c", "d", "e"] → unchanged
// splice: modifies the array
letters.splice(1, 2); // deletes 2 elements starting at index 1
console.log(letters); // ["a", "d", "e"]
letters.splice(1, 0, "X", "Y"); // inserts "X" and "Y" at index 1 without deleting anything
console.log(letters); // ["a", "X", "Y", "d", "e"]const a = [1, 2];
const b = [3, 4];
const merged = [...a, ...b]; // [1, 2, 3, 4]
const copy = [...a]; // independent copy of a
const withAddition = [...a, 99]; // [1, 2, 99] without modifying a
console.log(a); // [1, 2] → still unchangedThe forEach method lets you run a function for each element of an array, without having to write a classicfor loop.
const fruits = ["apple", "banana", "kiwi"];
fruits.forEach((fruit, index) => {
console.log(index, "→", fruit);
});
// 0 → apple
// 1 → banana
// 2 → kiwiThese three methods are among the most used in all of modern JavaScript. Unlike push or pop, theynever modify the original array: they always return a new result.
map transforms each element of an array and returns a new array of the same length.
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((n) => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
console.log(numbers); // [1, 2, 3, 4, 5] → unchangedfilter only keeps the elements that satisfy a given condition.
const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter((n) => n % 2 === 0);
console.log(evens); // [2, 4]reduce combines all the elements of an array into a single value (a sum, an average, a total...).
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((total, n) => total + n, 0);
console.log(sum); // 15
// You can chain several methods one after another:
const sumOfEvens = numbers
.filter((n) => n % 2 === 0)
.reduce((total, n) => total + n, 0);
console.log(sumOfEvens); // 6const numbers = [3, 7, 2, 9, 4];
numbers.find((n) => n > 5); // 7 (the first matching element)
numbers.findIndex((n) => n > 5); // 1 (the index of that element)
numbers.includes(9); // true (does the array contain 9?)
numbers.indexOf(2); // 2 (index of the value 2)find returns the first element found, or undefined if none matches.includes is the simplest method for checking whether a value is present.Two other methods answer "yes or no" questions about the whole array:some (does at least one element satisfy the condition?) and every (do all the elements satisfy it?).
const ages = [17, 22, 35];
console.log(ages.some((age) => age < 18)); // true (at least one minor)
console.log(ages.every((age) => age >= 18)); // false (not all adults)const numbers = [5, 3, 8, 1, 9];
const sorted = [...numbers].sort((a, b) => a - b); // ascending sort
console.log(sorted); // [1, 3, 5, 8, 9]
const sortedDesc = [...numbers].sort((a, b) => b - a); // descending sort
console.log(sortedDesc); // [9, 8, 5, 3, 1]The ... (spread) operator is used here to copy the array before sorting it, because sort normally modifies the original array — a good practice to avoid unexpected side effects.
Be careful: without a comparison function,sort sorts the elements as text, which gives surprising results for numbers:
console.log([10, 9, 1, 100].sort()); // [1, 10, 100, 9] → alphabetical order!
console.log([10, 9, 1, 100].sort((a, b) => a - b)); // [1, 9, 10, 100] → correct
// For text, the default sort is fine
console.log(["kiwi", "banana", "apple"].sort()); // ["apple", "banana", "kiwi"]
// Reversing the order of an array
// (reverse also modifies the original array)
console.log([1, 2, 3].reverse()); // [3, 2, 1]0: the first element is array[0], not array[1].const makes the content of an array immutable.sort() on numbers without a comparison function.const b = a: both variables then refer to the same array. Use [...a] for a real copy.map (which returns a new array) and forEach (which returns nothing).Exercise 1: map, filter, reduce, sort
Starting from the array [3, 7, 2, 9, 4, 6]:
filter to keep only the numbers greater than 4.reduce on that result to calculate their sum.map to create a new array containing the square of each number in the original array.sort to display the original array sorted in ascending order, without modifying the original.Exercise 2: managing a shopping list
Create an array groceries containing three products, then:
splice.includes whether "rice" is in the list.length.push, pop, shift, unshift and splice modify the original array.map, filter and reduce are the three most used methods for transforming data, without modifying the original array.find, includes, some and every let you search for and check elements.[...array] to copy or merge without side effects, and a comparison function with sort for numbers.