Home › Learn › JavaScript › Objects

Arrays of objects

Lesson 22 of 40. The shape most real data takes.

Records come as arrays of objects: [{ name: "Ann", age: 31 }, { name: "Ben", age: 27 }]. Everything from the arrays module applies, with the callback reaching into each object: users.map(u => u.name) collects a field, users.filter(u => u.age >= 18) selects, users.find(u => u.name === "Ann") looks one up, and reduce can total a field or find the record with the largest value.

Sorting records means comparing a field: users.sort((a, b) => a.age - b.age) for numbers, a.name.localeCompare(b.name) for strings.

const users = [{ name: "Ann", age: 31 }, { name: "Ben", age: 27 }];
console.log(users.map((u) => u.name));                 // ["Ann", "Ben"]
console.log(users.find((u) => u.age < 30).name);       // Ben

Your task

Write namesOf(users) returning the names, oldest(users) returning the user object with the highest age (null for an empty array), and cartTotal(items) returning the total of price * qty over an array of items like { name, price, qty }, rounded to two decimals.

Part of the final project. cartTotal adds up price times quantity over the items in an order. It is saved in this browser and loaded into Project: checkout when you get there.

Hint 1

users.map((u) => u.name)

Hint 2

users.reduce((best, u) => (u.age > best.age ? u : best), users[0]); cartTotal: reduce to the sum of item.price * item.qty starting at 0, then Math.round(total * 100) / 100.

Show the solution
function namesOf(users) {
  return users.map((u) => u.name);
}

function oldest(users) {
  if (users.length === 0) return null;
  return users.reduce((best, u) => (u.age > best.age ? u : best), users[0]);
}

function cartTotal(items) {
  const total = items.reduce((sum, item) => sum + item.price * item.qty, 0);
  return Math.round(total * 100) / 100;
}

    Runs in an isolated web worker in this tab; nothing is sent anywhere.