String Cartography explainer

Aim of the puzzle: Write a function that takes a string and returns an object that has each character of the string as a property, with each property containing an array of indices where the character appears.
Walk through of solution:
The function you write in this puzzle will take a string, and return an object that shows what characters are in the string and all of the indices where those characters appear. For example, let’s call the function on the string 'bookkeeper':


This will return an object that looks like this:

  b: [0],
  o: [1, 2],
  k: [3, 4],
  e: [5, 6, 8],
  p: [7],
  r: [9]

The object has a separate property for each character in the string. Inside each property is an array containing the index positions where the characters appear.

Start writing the function by creating an empty object inside the function. For example:

let map = {};

Then, add a classic for loop to iterate through the string.

for (let i = 0; i < string.length; i++) {


Inside the for loop, create another local variable to store the current character. For example:

let letter = string[i];

Then, use an if else statement (a ternary can also be used) to check if a property already exists in map for the current letter. If the property does not exist, it will be undefined, which is falsy. The if else statement will look something like this:

if (map[letter]) {

} else {


If the property already exists (meaning the current character has been seen before), then push the index of the current character to the array contained in the property. If it does not exist, create the array (with the index inside as the 1st item). It should look something like this:

if (map[letter]) {
} else {
  map[letter] = [i];

Finally, at the end of the function, return map.
Javascript Concepts: Functions, Objects, Properties, Strings, For Loops, If Statements, Truthiness