← JS Mastery | Module 4: Objects & Arrays Arrays & Array Methods
Module 4

Arrays & Array Methods

⏱ 24 min read ● Beginner 🆓 Free

Arrays — Ordered Lists

Arrays store ordered collections of values. Unlike objects where you access values by name, you access array elements by their numeric index (starting at 0). Arrays are one of the most important data structures you'll use every day.

// Creating arrays
const fruits = ["apple", "banana", "cherry"];
const numbers = [1, 2, 3, 4, 5];
const mixed = [1, "hello", true, null, { name: "Alice" }];
const empty = [];
const matrix = [[1,2],[3,4],[5,6]];  // nested array

// Accessing elements
console.log(fruits[0]);   // "apple"  — first element
console.log(fruits[2]);   // "cherry" — third element
console.log(fruits[-1]);  // undefined — negative index doesn't work in JS!
console.log(fruits.at(-1)); // "cherry" — .at() supports negative (ES2022)

// Array length
console.log(fruits.length);     // 3
console.log(fruits[fruits.length - 1]); // "cherry" — last element
console.log(fruits.at(-1));     // "cherry" — cleaner

// Modifying arrays
fruits[1] = "mango";   // replace at index
fruits[10] = "grape";  // creates sparse array with empty slots!
// Avoid sparse arrays — always use push/splice

Array Mutation Methods

const arr = [1, 2, 3];

// Add/remove at end
arr.push(4, 5);     // [1,2,3,4,5] — adds to end, returns new length
arr.pop();          // [1,2,3,4] — removes from end, returns removed item

// Add/remove at beginning
arr.unshift(0);     // [0,1,2,3,4] — adds to start
arr.shift();        // [1,2,3,4] — removes from start, returns removed item

// splice — modify anywhere
arr.splice(1, 2);        // remove 2 items at index 1: [1,4]
arr.splice(1, 0, 2, 3);  // insert at index 1: [1,2,3,4]
arr.splice(2, 1, 99);    // replace 1 item at index 2: [1,2,99,4]

// sort — MUTATES the array!
const words = ["banana", "apple", "cherry"];
words.sort();  // alphabetical: ["apple","banana","cherry"]

const nums = [10, 1, 21, 2];
nums.sort();           // ["1","10","2","21"] — WRONG! sorts as strings
nums.sort((a,b) => a-b); // [1,2,10,21] — CORRECT numeric sort

// reverse — mutates:
[1,2,3,4,5].reverse();  // [5,4,3,2,1]

// fill — fill with value:
new Array(5).fill(0);    // [0,0,0,0,0]
[1,2,3,4,5].fill(0, 2, 4);  // [1,2,0,0,5]

Non-Mutating Methods (Return New Array)

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

// slice — extract portion (doesn't modify original!)
original.slice(1, 3);    // [2, 3]
original.slice(-2);      // [4, 5] — last 2 items
original.slice();        // [1,2,3,4,5] — copy entire array

// concat — merge arrays
[1,2].concat([3,4], [5,6]);  // [1,2,3,4,5,6]
// Spread is more readable: [...[1,2], ...[3,4]]

// map, filter, reduce (covered in loops lesson)
const doubled = original.map(n => n * 2);       // [2,4,6,8,10]
const evens = original.filter(n => n % 2 === 0); // [2,4]
const sum = original.reduce((acc,n) => acc+n, 0); // 15

// flat and flatMap (ES2019)
[[1,2],[3,4]].flat();           // [1,2,3,4]
[1,[2,[3,[4]]]].flat(Infinity); // [1,2,3,4]
[1,2,3].flatMap(n => [n, n*2]); // [1,2,2,4,3,6]

// find and findIndex
original.find(n => n > 3);       // 4
original.findIndex(n => n > 3);  // 3 (index)
original.findLast(n => n < 4);   // 3 (from end, ES2023)

// indexOf and includes
original.indexOf(3);        // 2
original.includes(3);       // true
original.lastIndexOf(3);    // 2

// join — array to string
["a","b","c"].join("-");    // "a-b-c"
["a","b","c"].join();       // "a,b,c"
["a","b","c"].join("");     // "abc"

Array Spread and Useful Patterns

// Spread creates a shallow copy
const original = [1, 2, 3];
const copy = [...original];
copy.push(4);
console.log(original);  // [1,2,3] — unchanged!

// Spread to combine arrays
const combined = [...[1,2], ...[3,4], 5];  // [1,2,3,4,5]

// Array.from() — create array from iterable
Array.from("hello");            // ["h","e","l","l","o"]
Array.from({length: 5}, (_, i) => i); // [0,1,2,3,4]
Array.from(new Set([1,2,2,3])); // [1,2,3] — deduplicate!

// Removing duplicates:
const withDups = [1,2,2,3,3,4];
const unique = [...new Set(withDups)];  // [1,2,3,4]

// Sorting objects by property:
const users = [
  {name:"Charlie",age:25},{name:"Alice",age:30},{name:"Bob",age:20}
];
users.sort((a,b) => a.name.localeCompare(b.name));
users.sort((a,b) => a.age - b.age);

⚡ Key Takeaways

🎯 Practice Exercises

EXERCISE 1

Given an array of student objects with name and grade, sort by grade descending, filter for passing grades (>= 60), and map to just the names.

EXERCISE 2 — CHALLENGE

Implement a function groupBy(arr, key) that groups array items by a property. E.g., group people by city returns { "NYC": [...], "LA": [...] }.

← Objects