Home > Net >  How to add two values to the same index in map type array
How to add two values to the same index in map type array

Time:07-10

let wordsArray;
let indexArray = []; 
let index;
let myMap = new Map();
const Storage = function(userInput){
    wordsArray = userInput.split(' ');
    
    //remove ',' and '.'
    for( let i = 0; i < wordsArray.length ; i   ){
        if(wordsArray[i].endsWith(',') || wordsArray[i].endsWith('.') || wordsArray[i].endsWith('!') || wordsArray[i].endsWith(':')) {
            let temp = wordsArray[i];
            wordsArray[i] = temp.slice(0, temp.length - 1 );
        }

        //ToLowerCase
        let temp = wordsArray[i]
        wordsArray[i] = temp.toLowerCase();

        //IndexCreation
        let letter = wordsArray[i].slice(0,1); 
        indexArray.push(letter);
       
        //Add to Array
        myMap.set(letter,wordsArray[i]);
    }
    console.log(myMap);
    
    
}
Storage("Hello, my name is Gleb. My hobby is to learn Javascript");
Expected output h stands for hello and hobby, but actually it contains only last word - hobby. How can i add word to index, instead of repleasing?

CodePudding user response:

The elements of your "index" map should be arrays rather than strings. When adding a word, check if the first letter already exists in the map, and if not, initialize it to an empty array. Then, add a word to map[letter]:

let index = new Map

word = 'hello'
letter = word[0]

if (!index.has(letter))
    index.set(letter, [])
index.get(letter).push(word)

word = 'hobby'
letter = word[0]

if (!index.has(letter))
    index.set(letter, [])
index.get(letter).push(word)


console.log([...index])

CodePudding user response:

//Add to Array
    if (myMap.has(letter)){
        let temp = myMap.get(letter);
        temp = [temp,wordsArray[i]]
        myMap.set(letter, temp)
        
    }else{
        myMap.set(letter, wordsArray[i]);
    }
  • Related