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]
};

Example

Following is the code −

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));

Output

Following is the output in the console −

{ c: [ 0 ], a: [ 1 ], n: [ 2, 3 ], o: [ 4 ], t: [ 5 ] }

Updated on: 18-Sep-2020

327 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements