Everyone Can Learn Program
中文 Start learning
Core · FrontendLesson 6 of 8Free to read

Arrays, objects and JSON · Frontend: HTML, CSS and JavaScript

How do you work with lists of things, like the products in a shop?

Course contents

Why you need it

Nearly all data a page shows arrives as arrays of objects: products, messages, search results. Turning that data into what's on screen means filtering it, transforming it and adding it up, and filter, map and reduce do exactly that in one readable line each.

The intuition

An object groups named values; an array is an ordered list:

const lamp = { name: "Lamp", price: 30 };
const prices = [30, 120, 45];

Read a value with a dot: lamp.price; an item by position: prices[0].

Array methods take a small function and apply it to every item, returning something new (the original array is untouched):

MethodReturns
filter(x => test)the items where the test is true
map(x => newValue)one new value per item
reduce((acc, x) => …, start)one value built from all items
find(x => test)the first match, or undefined

... (spread) copies: [...list, item] is a new array with one more item, { ...obj, price: 9 } a new object with one field changed.

JSON is how objects travel over the network: JSON.stringify(obj) turns an object into text, JSON.parse(text) turns it back.

Definition

Array method

A function such as filter, map or reduce that walks the array for you and returns a new result.

Spread (...)

Copies the items of an array or the fields of an object into a new one.

JSON

A text format for data: objects in { }, arrays in [ ], strings in double quotes. APIs send and receive it.

Examples

Filter, then map

Try it yourself

Keep the products in stock, then keep just their names.

const products = [
  { name: "Lamp", price: 30, inStock: true },
  { name: "Desk", price: 120, inStock: false },
  { name: "Chair", price: 45, inStock: true },
];
const available = products.filter(p => p.inStock);
const names = available.map(p => p.name);
console.log(names);
console.log(products[1].price);
Output
[ 'Lamp', 'Chair' ]
120
Step by step
  1. L6Keeps Lamp and Chair: the items where p.inStock is true.
  2. L7Turns each product into just its name.
  3. L8Strings inside an array print with quotes.[ 'Lamp', 'Chair' ]
  4. L9The original array still has all three; index 1 is the desk.120

Add it all up

Try it yourself

reduce carries a running total from item to item.

const prices = [30, 120, 45];
const total = prices.reduce((sum, price) => sum + price, 0);
console.log(total);
console.log(Math.max(...prices));
Output
195
120
Step by step
  1. L2sum starts at 0, then 0+30, 30+120, 150+45.195
  2. L4...prices spreads the array into separate arguments: Math.max(30, 120, 45).120

Copies and JSON

Try it yourself

Change a copy, not the original, and turn objects into text.

const user = { name: "Ada", city: "London" };
const moved = { ...user, city: "Paris" };
console.log(user.city, moved.city);

const { name, city } = moved;
console.log(name, city);

const text = JSON.stringify(moved);
console.log(text);
console.log(JSON.parse(text).name);
Output
London Paris
Ada Paris
{"name":"Ada","city":"Paris"}
Ada
Step by step
  1. L2A new object: every field of user, then city replaced.
  2. L3The original is untouched.London Paris
  3. L5Destructuring pulls fields out into variables.
  4. L8JSON text: keys and strings in double quotes.{"name":"Ada","city":"Paris"}

Common mistakes

Braces without return

x => x * 2 returns the value, but x => { x * 2 } returns nothing (undefined). With braces, write return.

sort() sorts as text

[10, 9, 1].sort() gives [1, 10, 9]. For numbers pass a compare function: .sort((a, b) => a - b).

Comparing objects with ===

{a: 1} === {a: 1} is false: === on objects asks "is it the same object?", not "same contents?".

Quick quiz

1. What does this print?

const doubled = [1, 2, 3].map(x => { x * 2 });
console.log(doubled);
  1. A
    [ 2, 4, 6 ]
  2. B
    [ undefined, undefined, undefined ]
  3. C
    []
Show the answer

Answer: B

The braces make a function body with no return, so every item becomes undefined.

2. What does this print?

console.log([10, 9, 1].sort());
  1. A
    [ 1, 9, 10 ]
  2. B
    [ 1, 10, 9 ]
  3. C
    [ 10, 9, 1 ]
Show the answer

Answer: B

Without a compare function, sort compares text: "10" comes before "9" because "1" < "9".

Practice

3 exercises in three steps: predict what a program prints, change a program to meet a new requirement, then write one from scratch. Your code runs in the browser and is checked the moment you submit.

  1. PredictWhat's in the cart?

    Type exactly what this prints.

  2. ModifyNames of active users

    activeNames should return the names of the active users, but it returns a list of undefined. Fix it.

  3. WriteTotal per customer

    Write totalsByCustomer(orders). Each order looks like { customer: "ann", amount: 20 }. Return an object with each customer's total:

    totalsByCustomer([
      { customer: "ann", amount: 20 },
      { customer: "bo", amount: 5 },
      { customer: "ann", amount: 10 },
    ])
    // { ann: 30, bo: 5 }

Practise this lesson

Open the interactive lesson to edit and run these examples and solve the exercises with instant feedback. Free to start, no sign-up.

Interactive lessons open in order. If you have not done the earlier ones yet, you start at the course map.

Terms in this lesson

TermChineseDefinition
Array数组An ordered list of values: [1, 2, 3].
Object对象Named values grouped together: { name: "Ada" }.
JSONJSONA text format for data, used by almost every web API.
Spread展开运算符... copies the items of an array or the fields of an object.