Array Reduce to Object in JavaScript

Level 4207 keystrokes

Uses reduce() to transform an array of objects into a lookup object indexed by id.

JavaScript code

// Create an array of item objects with id and name
1const items = [
2 { id: 1, name: "Apple" },
3 { id: 2, name: "Banana" },
4 { id: 3, name: "Cherry" }
5];
6
// reduce() accumulates values into a single result
// acc is the accumulator (starts as {})
// item is the current element being processed
7const byId = items.reduce((acc, item) => {
// Use the id as key and name as value
// This creates { 1: "Apple", 2: "Banana", ... }
8 acc[item.id] = item.name;
// Must return the accumulator for the next iteration
9 return acc;
// {} is the initial value of the accumulator
10}, {});
11
// Output the lookup object
12console.log(byId);

Output

{ '1': 'Apple', '2': 'Banana', '3': 'Cherry' }
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • ,× 7
  • :× 6
  • "× 6
  • ;× 5
  • {× 5
  • }× 5
  • .× 4
  • =× 4
  • (× 3
  • )× 3

More JavaScript examples at level 4

← JavaScript typing practice