- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ] }
Advertisements