Skip to content
KALANBLON
Show contents

Chapter 1 of 6 · 20 min

Objects and array methods

By the end of this chapter, you'll be able to

  • Create an object, read and change its properties
  • Transform an array with map and filter it with filter
  • Compute a single result with reduce and search with find
  • Convert data to JSON and back

Objects

An object groups named values, called properties. It's the equivalent of a dictionary in Python:

const book = {
  title: "Ambiguous Adventure",
  author: "Cheikh Hamidou Kane",
  year: 1961,
  available: true,
};
console.log(book.title, "-", book.year);
book.available = false;
book.pages = 191;
console.log(Object.keys(book).join(", "));
const { title, author } = book;
console.log(`${title}, by ${author}`);
Ambiguous Adventure - 1961
title, author, year, available, pages
Ambiguous Adventure, by Cheikh Hamidou Kane
  • You read a property with a dot: book.title. You change it or add one by simple assignment.
  • const prevents reassigning the variable book, but not changing the object's content.
  • Object.keys(object) returns the array of property names.
  • const { title, author } = book; is destructuring: it creates two variables from the properties of the same name.

Array methods

An array of objects is an application's daily bread. Rather than writing a loop each time, you use methods that take a function as an argument. Most often it's written as an arrow function: (o) => o.price is a small function that receives o and returns o.price.

const orders = [
  { customer: "Ama", dish: "jollof", price: 4.5, delivered: true },
  { customer: "Bruno", dish: "feijoada", price: 7, delivered: false },
  { customer: "Chen", dish: "jollof", price: 4.5, delivered: true },
  { customer: "Dina", dish: "falafel", price: 3, delivered: false },
];

const waiting = orders.filter((o) => !o.delivered);
console.log(waiting.map((o) => o.customer).join(", "));

const total = orders.reduce((sum, o) => sum + o.price, 0);
console.log("Total:", total);

const firstJollof = orders.find((o) => o.dish === "jollof");
console.log(firstJollof.customer);

const lines = orders.map((o) => `${o.customer}: ${o.dish} (€${o.price.toFixed(2)})`);
console.log(lines[1]);
console.log(orders.some((o) => o.price > 6), orders.every((o) => o.price > 2));
Bruno, Dina
Total: 19
Ama
Bruno: feijoada (€7.00)
true true
MethodReturnsUse
map(f)a new array of the same lengthtransform each item
filter(f)a new, shorter arraykeep the items for which f returns true
find(f)the first item found, or undefinedsearch for an item
reduce(f, start)a single valuetotal, maximum, grouping
some(f) / every(f)true or false"at least one" / "all"

None of these methods changes the original array: they create a new one or return a value. toFixed(2) displays a number with two decimals.

The array is finished: reduce returns the last accumulated value, 19.

Step 6 of 6
Text description of the animation
  1. reduce calls the function once per order, passing it the result accumulated so far.
  2. First call: sum is the starting value, 0. Ama's order costs 4.5.
  3. The result 4.5 becomes the new sum. Bruno's order: 7.
  4. Chen's order: 4.5.
  5. Last order, Dina's: 3.
  6. The array is finished: reduce returns the last accumulated value, 19.

Copying without surprises

Assigning an object or array to another variable doesn't copy it: both variables refer to the same object. For a real copy, you use the spread syntax ...:

const original = { name: "Ama", grades: [12, 15] };
const copy = original;
copy.name = "Kofi";
console.log(original.name);

const realCopy = { ...original, grades: [...original.grades] };
realCopy.grades.push(18);
console.log(original.grades.length, realCopy.grades.length);
Kofi
2 3

{ ...original } creates a new object with the same properties, and [...array] a new array. Careful: this copy only goes one level deep. That's why grades is copied separately too.

JSON

To send data to a server or store it in the browser, you turn it into JSON text:

const text = JSON.stringify({ city: "Accra", temperature: 31, rain: false });
console.log(text);
const weather = JSON.parse(text);
console.log(weather.city, typeof weather.temperature);
{"city":"Accra","temperature":31,"rain":false}
Accra number

Your turn

Analyse a shop's salesJavaScript

Output

Click “Run” to execute your code.

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Worked exercise

Worked exercise: the weather summary

Write a function summary(readings) that receives an array of { city, temperature } and returns an object with: the list of cities at 25 °C or more (hot), the average temperature rounded to one decimal (average) and the name of the coldest city (coldest). Use filter, map and reduce, with no for loop.

Hint 1
The hot cities: filter to keep the right readings, then map to keep only the name.
Hint 2
The coldest: reduce with no starting value, keeping at each step the colder reading between the accumulated one and the current one. To round to one decimal: Math.round(x * 10) / 10.
Show the solution and common mistakes
const readings = [
  { city: "Accra", temperature: 31 },
  { city: "Oslo", temperature: -4 },
  { city: "Lima", temperature: 19 },
  { city: "Hanoi", temperature: 27 },
];

function summary(readings) {
  const hot = readings.filter((r) => r.temperature >= 25).map((r) => r.city);
  const average = readings.reduce((s, r) => s + r.temperature, 0) / readings.length;
  const coldest = readings.reduce((min, r) => (r.temperature < min.temperature ? r : min));
  return { hot, average: Math.round(average * 10) / 10, coldest: coldest.city };
}

const s = summary(readings);
console.log(s.hot.join(" and "));
console.log(s.average, s.coldest);
Accra and Hanoi
18.3 Oslo

{ hot, average: … } is a shorthand: hot on its own means hot: hot.

Common mistakes:

  • Using map to filter: you get an array of true/false or undefined, the same length as the original.
  • Forgetting the starting value 0 in the average's reduce: here it would work by luck, but on an empty array, reduce with no starting value raises a TypeError.

Summary

  1. 1An object groups named properties; you read and change them with a dot.
  2. 2map transforms, filter keeps, find searches, reduce computes a single value.
  3. 3These methods don't change the original array.
  4. 4Assigning an object doesn't copy it: use { ...obj } and [...arr].
  5. 5Input is text: convert it with Number before calculating or sorting.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.