Mapping the letter of a string to an object of arrays - JavaScript

Given a string, we are required to write a function that creates an object that stores the indexes of each letter in an array. The letters (elements) of the string must be the keys of object.

The indexes should be stored in an array and those arrays are values.

For example, if the input string is:

const str = 'cannot';

Then the output should be:

const output = {
    'c': [0],
    'a': [1], 
    'n': [2, 3],
    'o': [4],
    't': [5]
};

Using for Loop with hasOwnProperty

This approach iterates through each character and checks if it already exists in the object:

const str = 'cannot';
const mapString = str => {
    const map = {};
    for(let i = 0; i < str.length; i++){
        if(map.hasOwnProperty(str[i])){
            map[str[i]] = map[str[i]].concat(i);
        }else{
            map[str[i]] = [i];
        };
    };
    return map;
};
console.log(mapString(str));
{ c: [ 0 ], a: [ 1 ], n: [ 2, 3 ], o: [ 4 ], t: [ 5 ] }

Using forEach with Spread Operator

A more modern approach using array methods:

const str = 'cannot';
const mapString = str => {
    const map = {};
    [...str].forEach((char, index) => {
        map[char] = map[char] ? [...map[char], index] : [index];
    });
    return map;
};
console.log(mapString(str));
{ c: [ 0 ], a: [ 1 ], n: [ 2, 3 ], o: [ 4 ], t: [ 5 ] }

Using reduce Method

The most concise functional approach:

const str = 'cannot';
const mapString = str => {
    return [...str].reduce((acc, char, index) => {
        acc[char] = acc[char] ? [...acc[char], index] : [index];
        return acc;
    }, {});
};
console.log(mapString(str));
{ c: [ 0 ], a: [ 1 ], n: [ 2, 3 ], o: [ 4 ], t: [ 5 ] }

Comparison

Method Readability Performance Modern Syntax
for loop Good Best Traditional
forEach Better Good Modern
reduce Best Good Functional

Conclusion

All three methods effectively map string characters to their index arrays. Choose the for loop for performance-critical code or reduce for functional programming style.

Updated on: 2026-03-15T23:18:59+05:30

505 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements