BeginnerJavaScript · Lesson 5 of 7

Arrays & Objects

Store data in arrays and objects; transform it with map, filter, find and reduce; destructuring and spread.

An array is an ordered list: [78, 64, 91]. An object groups named values: { name: "Amina", score: 88 }. An array of objects is the everyday way to hold records, such as students or products.

Array methods replace most manual loops: filter keeps matching items, map transforms each item, find returns the first match, some/every test conditions, reduce combines items into one value, and sort orders them (copy first with [...arr] or use toSorted).

Destructuring pulls values out (const { name, score } = student), and the spread syntax ... copies or merges arrays and objects without changing the originals.

students.jsJavaScript
const students = [
  { id: 1, name: "Amina", form: 4, score: 88 },
  { id: 2, name: "Baraka", form: 3, score: 54 },
  { id: 3, name: "Neema", form: 4, score: 71 },
];

const formFour = students.filter((s) => s.form === 4).map((s) => s.name);
const top = students.find((s) => s.score >= 85);
const total = students.reduce((sum, s) => sum + s.score, 0);
const ranked = [...students].sort((a, b) => b.score - a.score);

console.log(formFour);                         // [ 'Amina', 'Neema' ]
console.log(top.name, (total / students.length).toFixed(1));
console.log(ranked.map((s) => s.name).join(" > "));
console.log(students.some((s) => s.score < 30), students.every((s) => s.form >= 3));

const { name, score } = students[0];           // destructuring
console.log(`${name} scored ${score}`);

const updated = { ...students[1], score: 60 };  // copy with one change
console.log(updated, students[1].score);        // original still 54

const allScores = [...students.map((s) => s.score), 95];
console.log(Math.max(...allScores));            // 95
console.log(Object.keys(students[0]), Object.entries({ a: 1, b: 2 }));
Runs in your browser · JavaScript

Key points

  • Arrays hold ordered lists; objects hold named properties.
  • filter, map, find, reduce cover most data processing.
  • Spread (...) copies instead of changing the original — safer code.

Exercise

Given an array of products (name, price, quantity, category), produce: the names under 5,000 TSh, the total stock value, the most expensive product, and an object counting products per category (hint: reduce).

Show solution

Try the exercise yourself first — then compare your approach with this one.

filter + map find the cheap names, reduce adds up price × quantity, a reduce that keeps the pricier item finds the most expensive one, and another reduce builds an object counting products per category.

products.jsJavaScript
const products = [
  { name: "Exercise book", price: 1500, quantity: 200, category: "Stationery" },
  { name: "Scientific calculator", price: 35000, quantity: 12, category: "Electronics" },
  { name: "Geometry set", price: 4500, quantity: 40, category: "Stationery" },
  { name: "School bag", price: 25000, quantity: 15, category: "Bags" },
];

const cheap = products.filter((p) => p.price < 5000).map((p) => p.name);
const stockValue = products.reduce((sum, p) => sum + p.price * p.quantity, 0);
const mostExpensive = products.reduce((best, p) => (p.price > best.price ? p : best));
const perCategory = products.reduce((counts, p) => {
  counts[p.category] = (counts[p.category] ?? 0) + 1;
  return counts;
}, {});

console.log(cheap);                                  // [ 'Exercise book', 'Geometry set' ]
console.log(stockValue.toLocaleString("en-US"));     // 1,275,000
console.log(mostExpensive.name);                     // Scientific calculator
console.log(perCategory);                            // { Stationery: 2, Electronics: 1, Bags: 1 }
Runs in your browser · JavaScript

Check your understanding

  1. Which method returns the first item that matches a condition?

  2. What does const { name, score } = student; do?

  3. Why copy with [...students].sort(...) instead of students.sort(...)?

  4. What does { ...student, score: 60 } create?

Ask AI