Objects, arrays of objects and array methods
Group related data in JavaScript objects, work with lists of objects like real app data, and transform them with the array methods map, filter, find, reduce and sort.
🎯 By the end of this lesson you will be able to:
- Create objects and read, add and change their properties
- Loop over arrays of objects, the shape most app data takes
- Use map, filter, find, reduce and sort with arrow functions
Outline
What you'll learn and why it matters
A product is not just a name: it has a price, a category and a stock level. An object keeps those related values together under one name. A list of products is an array of objects, which is exactly the shape of the data you get from shops, apps and APIs. The array methods in this lesson are what professional JavaScript developers use every day to work with that data.
Objects
An object is written with curly braces and holds properties: key: value pairs separated by commas.
const product = {
name: "Masala chai",
price: 40,
inStock: true,
};
console.log(product);
console.log(product.name);
console.log(product["price"]);
product.price = 45;
product.category = "drinks";
console.log(product);Console (Chrome and Edge)
{name: 'Masala chai', price: 40, inStock: true}
Masala chai
40
{name: 'Masala chai', price: 45, inStock: true, category: 'drinks'}| Code | Does |
|---|---|
product.name | Reads a property (dot notation; use this normally) |
product["price"] | Reads a property by a name in a string, handy when the name is in a variable |
product.price = 45 | Changes a property |
product.category = "drinks" | Adds a new property |
product.colour | A property that does not exist gives undefined |
Arrays of objects
const menu = [
{ name: "Masala chai", price: 40, category: "drinks" },
{ name: "Filter coffee", price: 50, category: "drinks" },
{ name: "Banana bread", price: 60, category: "snacks" },
{ name: "Samosa", price: 25, category: "snacks" },
];
for (const item of menu) {
console.log(`${item.name}: ₹${item.price}`);
}Console (Chrome and Edge)
Masala chai: ₹40 Filter coffee: ₹50 Banana bread: ₹60 Samosa: ₹25
Each item in the loop is one object, so you read its properties with a dot. We will use this menu for the rest of the lesson.
Array methods: map, filter, find, reduce
These methods take a small function, usually an arrow function, and call it for every item. They return a new value and leave the original array unchanged.
const menu = [
{ name: "Masala chai", price: 40, category: "drinks" },
{ name: "Filter coffee", price: 50, category: "drinks" },
{ name: "Banana bread", price: 60, category: "snacks" },
{ name: "Samosa", price: 25, category: "snacks" },
];
const names = menu.map((item) => item.name);
console.log(names);
const drinks = menu.filter((item) => item.category === "drinks");
console.log(drinks.length);
const bread = menu.find((item) => item.name === "Banana bread");
console.log(bread.price);
const total = menu.reduce((sum, item) => sum + item.price, 0);
console.log(total);Console (Chrome and Edge)
(4) ['Masala chai', 'Filter coffee', 'Banana bread', 'Samosa'] 2 60 175
| Method | Returns | Question it answers |
|---|---|---|
map(fn) | A new array, same length, each item transformed | What does each item become? |
filter(fn) | A new array with only the items where fn returns true | Which items match? |
find(fn) | The first matching item, or undefined | Which one item matches? |
reduce(fn, start) | One value built up from all items | What is the total (or count, or maximum)? |
some(fn) / every(fn) | true or false | Does any / every item match? |
In reduce((sum, item) => sum + item.price, 0), sum starts at 0 and each round returns the new running total. It is the accumulator pattern from lesson 5, in one line.
Chaining methods
Because filter and map return arrays, you can chain them:
const menu = [
{ name: "Masala chai", price: 40, category: "drinks" },
{ name: "Filter coffee", price: 50, category: "drinks" },
{ name: "Banana bread", price: 60, category: "snacks" },
{ name: "Samosa", price: 25, category: "snacks" },
];
const drinksTotal = menu
.filter((item) => item.category === "drinks")
.map((item) => item.price)
.reduce((sum, price) => sum + price, 0);
console.log(drinksTotal);
const labels = menu
.filter((item) => item.price < 50)
.map((item) => `${item.name} (₹${item.price})`);
console.log(labels.join(", "));Console (Chrome and Edge)
90 Masala chai (₹40), Samosa (₹25)
Sorting
sort reorders an array. For numbers, give it a compare function: (a, b) => a.price - b.price sorts from low to high. Copy the array first with [...menu] so the original order is kept:
const menu = [
{ name: "Masala chai", price: 40 },
{ name: "Filter coffee", price: 50 },
{ name: "Banana bread", price: 60 },
{ name: "Samosa", price: 25 },
];
const cheapestFirst = [...menu].sort((a, b) => a.price - b.price);
console.log(cheapestFirst.map((item) => item.name).join(", "));
console.log(menu[0].name);Console (Chrome and Edge)
Samosa, Masala chai, Filter coffee, Banana bread Masala chai
Practice
Guided exercise
Class results
Given an array of students with name and marks, print the names of those who scored 50 or more (joined with commas), and the class average.
- Use
filterto keep students withmarks >= 50, thenmapto their names, thenjoin(", "). - Use
reduceto add up all the marks, starting from 0. - Divide by
students.lengthfor the average.
Show the solution
const students = [
{ name: "Asha", marks: 78 },
{ name: "Ravi", marks: 45 },
{ name: "Meera", marks: 91 },
{ name: "Kofi", marks: 62 },
];
const passed = students
.filter((s) => s.marks >= 50)
.map((s) => s.name)
.join(", ");
console.log(`Passed: ${passed}`);
const totalMarks = students.reduce((sum, s) => sum + s.marks, 0);
console.log(`Average: ${totalMarks / students.length}`);Console (Chrome and Edge)
Passed: Asha, Meera, Kofi Average: 69
How to get there: filter picks the students, map turns each object into a name, and join makes one line of text. reduce adds 78 + 45 + 91 + 62 = 276, and 276 / 4 = 69.
Your turn
Most expensive item
Using the four-item menu from this lesson, print the name of the most expensive item. Use reduce or sort.
Show the solution
const menu = [
{ name: "Masala chai", price: 40 },
{ name: "Filter coffee", price: 50 },
{ name: "Banana bread", price: 60 },
{ name: "Samosa", price: 25 },
];
const priciest = menu.reduce((best, item) => (item.price > best.price ? item : best));
console.log(priciest.name);Console (Chrome and Edge)
Banana bread
How to get there: Without a start value, reduce starts with the first item as best and keeps whichever of best and item is pricier. Sorting a copy from high to low and taking item 0 also works.
Common mistakes
Forgetting return in a map or filter arrow function with braces
You see: You get an array of undefined, or an empty array
Fix: Use the short form (x) => x.price, or write return inside braces.
Using = instead of === inside filter
You see: Every item matches, and the data gets changed
Fix: Compare with ===.
Expecting find to return an array
You see: find(...).length is undefined
Fix: find returns one item; use filter for several.
Leaving out reduce's start value with an empty array
You see: TypeError: Reduce of empty array with no initial value
Fix: Give a start value such as 0.
Sorting numbers without a compare function
You see: 10 comes before 9
Fix: Use sort((a, b) => a - b).
Recap
- Objects group related values as
key: valueproperties; read them withobject.key. - Most app data is an array of objects; loop over it with for...of.
- map transforms, filter selects, find picks one, reduce combines, sort reorders.
- Chain methods for clear data pipelines; copy with
[...array]before sorting.
Key terms
- Object
- A collection of named properties, such as { name: "Asha", age: 20 }.
- Property
- One key and value inside an object.
- Callback
- A function passed to another function, such as the arrow function given to map.
Check your understanding
Answer all 4 questions, then check your answers to see an explanation for each one.
1. How do you read the `price` property of `item`?
2. What does `[1, 2, 3].map((n) => n * 10)` return?
3. Which method gives you only the menu items under ₹50?
4. What does `[5, 10, 15].reduce((sum, n) => sum + n, 0)` return?
Mark this lesson complete
Finished this lesson?
When you have worked through the examples and exercises, mark it complete to save your progress.