javascriptintermediate10 minutes

Predict the Output of a Complex Array and Object Transformation

Analyze the provided JavaScript code snippet that manipulates arrays and objects with multiple steps. Predict the exact output produced by the code.

Challenge prompt

Given the following JavaScript code that processes an array of user objects, determine what the console.log output will be when the code is executed. Focus on understanding the transformations, map/filter usage, and combined operations on the data.

Guidance

  • Examine how the map() and filter() methods transform the array step-by-step.
  • Pay attention to how object properties are accessed and modified within callback functions.
  • Consider the order of operations and how chaining affects the intermediate results.

Hints

  • Remember that map() returns a new array based on the return value of its callback.
  • Filtering affects which elements continue in the chain, so consider which users are excluded.
  • Look carefully at nested properties and increments inside the map callbacks.

Starter code

const users = [
  { id: 1, name: 'Alice', scores: [10, 20, 30] },
  { id: 2, name: 'Bob', scores: [5, 15] },
  { id: 3, name: 'Charlie', scores: [] },
  { id: 4, name: 'David', scores: [8, 8, 8] }
];

const processedUsers = users
  .map(user => ({
    ...user,
    totalScore: user.scores.reduce((a, b) => a + b, 0),
    averageScore: user.scores.length ? user.scores.reduce((a, b) => a + b, 0) / user.scores.length : 0
  }))
  .filter(user => user.totalScore >= 20)
  .map(user => ({
    id: user.id * 2,
    name: user.name.toUpperCase(),
    totalScore: user.totalScore + 5,
    averageScore: parseFloat(user.averageScore.toFixed(2))
  }));

console.log(processedUsers);

Expected output

[ { id: 2, name: 'ALICE', totalScore: 65, averageScore: 20 }, { id: 8, name: 'DAVID', totalScore: 29, averageScore: 8 } ]

Core concepts

Array map()Array filter()Array reduce()Object destructuring and spread syntax

Challenge a Friend

Send this duel to someone else and see if they can solve it.