JavaScript - Arrays
Overview
Estimated time: 35–45 minutes
Arrays store ordered lists. Learn mutating vs non-mutating methods, iteration patterns, and common transformations.
Learning Objectives
- Create arrays and add/remove elements.
- Transform arrays with
map
/filter
/reduce
. - Copy/merge arrays safely and iterate predictably.
Prerequisites
Basics
const a = [1,2,3];
a.push(4); // [1,2,3,4]
a.pop(); // [1,2,3]
a.unshift(0); // [0,1,2,3]
a.shift(); // [1,2,3]
Slice vs splice
const b = [1,2,3,4];
b.slice(1,3); // [2,3] (non-mutating)
b.splice(1,2); // removes [2,3], b becomes [1,4]
Transformations
[1,2,3].map(x => x*2); // [2,4,6]
[1,2,3].filter(x => x%2===1); // [1,3]
[1,2,3].reduce((a,b) => a+b, 0); // 6
Copy/merge and iteration
const c = [...a]; // shallow copy
const d = [...a, ...b]; // merge
for (const x of d) { /* ... */ }
Search and test
[1,2,3].includes(2); // true
['a','b','c'].indexOf('b'); // 1
[1,2,3].find(x => x > 1); // 2
[1,2,3].findIndex(x => x > 1); // 1
// Modern engines:
// arr.findLast(pred), arr.findLastIndex(pred)
[1,2,3].some(x => x % 2 === 0); // true
[1,2,3].every(x => x > 0); // true
Sorting (mutating vs immutable)
const nums = [1, 10, 2];
nums.sort(); // ['1','10','2'] lexicographically -> [1,10,2]
nums.sort((a,b) => a - b); // numeric -> [1,2,10]
// Immutable copies (ES2023+)
const sorted = nums.toSorted((a,b) => a - b); // returns new array
const reversed = nums.toReversed(); // new reversed array
// Locale-aware string sort
['ä','a'].toSorted((a,b) => a.localeCompare(b, 'de'));
Flattening and mapping
const nested = [1, [2, [3, 4]]];
nested.flat(2); // [1,2,3,4]
['1','2','3'].flatMap(s => [Number(s)]); // [1,2,3]
Creation helpers and indexing
Array.from('hello'); // ['h','e','l','l','o']
Array.from({ length: 3 }, (_, i) => i); // [0,1,2]
Array.of(7); // [7]
const arr = [10, 20, 30];
arr.at(-1); // 30 (negative indexing)
Common Pitfalls
- Array holes behave oddly in iteration and methods; prefer dense arrays.
- Spread and slice are shallow copies; nested data remains shared.
Try it
Run this snippet to practice array transformations and deduplication:
Checks for Understanding
- What is the difference between
slice
andsplice
? - Why can sorting numbers with
Array.prototype.sort()
be surprising without a comparator?
Show answers
slice
returns a new array without mutating the original;splice
mutates the original by adding/removing items.- Sort converts elements to strings and compares lexicographically unless a numeric comparator is provided.
Exercises
- Given
[3,1,4,1,5]
, return a new array sorted ascending without mutating the original. - From
['Ada','Lin','Grace']
, create an array of greeting strings usingmap
.