JavaScript · Lesson 4 of 15

Arrays and Objects

map, filter, reduce, destructuring and spread for everyday data work.

  • Intermediate
  • 17 min read
  • 3 objectives

Before this lessonLesson 3: Functions and Scope

What you will learn

  • Transform arrays without loops
  • Destructure objects
  • Copy with spread

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 3 hours

Progress is saved in this browser. No account needed.

Tip: pressing Next marks this lesson complete automatically.

Arrays hold ordered lists and objects hold named properties. Almost all real JavaScript is transforming these two shapes. Learning the array methods well means you rarely need a manual for loop.

The two shapes of data

Almost all data in JavaScript is one of two shapes, or a mix of both. An array is an ordered list: ["red", "green", "blue"]. An object is a set of named properties: { name: "Ada", age: 36 }. A list of users is an array of objects. JSON, the format almost every web API speaks, is exactly these two shapes written as text.

const colors = ["red", "green", "blue"];
const user = { name: "Ada", age: 36 };
const users = [user, { name: "Linus", age: 54 }];

console.log(colors[1], user.name, users[1].age);
console.log(users.length);
Output
green Ada 54
2

Arrays

const nums = [1, 2, 3];
nums.push(4);         // add to end
nums.unshift(0);      // add to start
console.log(nums, nums.length, nums.at(-1));
console.log(nums.includes(3), nums.indexOf(3));
Output
[ 0, 1, 2, 3, 4 ] 5 4
true 3

map, filter, reduce

map transforms every item, filter keeps some, and reduce folds the list into one value. None of them change the original array; they return new ones, so they chain nicely.

const prices = [10, 25, 40, 5];
const withTax = prices.map((p) => p * 1.2);
const big = prices.filter((p) => p > 9);
const total = prices.reduce((sum, p) => sum + p, 0);
console.log(withTax);
console.log(big, total);
Output
[ 12, 30, 48, 6 ]
[ 10, 25, 40 ] 80

Also useful: find (first match), some / every (yes/no checks), sort and flat. Beware that sort() converts to strings by default and mutates the array; pass a comparer for numbers: nums.sort((a, b) => a - b).

Objects

const user = { name: "Ada", age: 36, tags: ["dev"] };
user.role = "admin";
console.log(user.name, user["age"]);
console.log(Object.keys(user));
console.log(Object.entries(user).length);
Output
Ada 36
[ 'name', 'age', 'tags', 'role' ]
4

Destructuring and spread

Destructuring unpacks values into variables; the spread operator ... copies or merges. Together they give you concise, immutable-style updates that React relies on.

const { name, ...rest } = user;
const [first, second] = [10, 20, 30];
const updated = { ...user, age: 37 };
const merged = [...[1, 2], ...[3]];
console.log(name, first, second, updated.age, merged);
Output
Ada 10 20 37 [ 1, 2, 3 ]

Grouping with reduce

const words = ["apple", "avocado", "banana"];
const byLetter = words.reduce((acc, w) => {
  (acc[w[0]] ??= []).push(w);
  return acc;
}, {});
console.log(byLetter);
Output
{ a: [ 'apple', 'avocado' ], b: [ 'banana' ] }

Changing arrays

const nums = [3, 1, 2];
nums.push(4);          // add to the end
nums.unshift(0);       // add to the start
const last = nums.pop();
nums.sort((a, b) => a - b);

console.log(nums, last);
console.log(nums.includes(2), nums.indexOf(3));
Output
[ 0, 1, 2, 3 ] 4
true 3

Thinking in map, filter and reduce

Instead of writing a loop that builds a new array by hand, describe the transformation. map changes every item, filter keeps some items, and reduce folds all items into one value. They chain together like a pipeline.

const orders = [
  { item: "book", price: 12, qty: 2 },
  { item: "pen", price: 2, qty: 10 },
  { item: "bag", price: 40, qty: 1 },
];

const totals = orders.map(o => o.price * o.qty);
const big = orders.filter(o => o.price * o.qty >= 24);
const grand = totals.reduce((sum, t) => sum + t, 0);

console.log(totals);
console.log(big.map(o => o.item));
console.log(grand);
Output
[ 24, 20, 40 ]
[ 'book', 'bag' ]
84

Finding one item

const users = [{ id: 1, name: "Ada" }, { id: 2, name: "Linus" }];
console.log(users.find(u => u.id === 2));
console.log(users.find(u => u.id === 9));
console.log(users.some(u => u.name === "Ada"), users.every(u => u.id > 1));
Output
{ id: 2, name: 'Linus' }
undefined
true false

Working with object properties

const car = { make: "Toyota", year: 2020 };
car.color = "blue";        // add
car.year = 2021;           // change
delete car.make;           // remove

console.log(car);
console.log(Object.keys(car), Object.values(car));
console.log("color" in car, car.wheels);
Output
{ year: 2021, color: 'blue' }
[ 'year', 'color' ] [ 2021, 'blue' ]
true undefined

Optional chaining for safe access

const data = { user: { profile: null } };

console.log(data.user.profile?.email);          // undefined, no crash
console.log(data.settings?.theme ?? "light");
Output
undefined
light

Key takeaways

  • Arrays are ordered lists; objects are named properties; real data is a mix.
  • map transforms, filter selects, reduce combines; chain them.
  • find, some and every answer questions about an array.
  • Use ?. and ?? to read data that might be missing.
// Write your solution here

Finished reading? Mark this lesson complete to track your progress.

Up next · Lesson 5Promises and async/awaitHandle work that finishes later: timers, fetch and error handling.