简体   繁体   中英

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

 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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM