Home > database >  Put all words that match a criterion to a Map
Put all words that match a criterion to a Map

Time:07-08

I'm really new at JavaScript and I faced the first issue that I'm trying to solve.

The goal of a program is to use first letter of each word as a key and the unique words as a values.

Here is the code:

function sortToMap(str){
    let lowerString = str.toLowerCase();
    let result = lowerString.split(" ");
    let myMap = new Map();

    for(let i = 0; i < result.length; i  ){
        myMap.set(result[i][0], result[i]);
    }
    return myMap;
}

let myString = "Test string to check How it Works and hopefully it is fine";
console.log(sortToMap(myString));

So it looks like this:

(Actual result)

Map(8) {
  't' => 'to',
  's' => 'string',
  'c' => 'check',
  'h' => 'hopefully',
  'i' => 'is',
  'w' => 'works',
  'a' => 'and',
  'f' => 'fine'
}

(Expected result)

Map(8) {
  't' => 'test', 'to',
  's' => 'string',
  'c' => 'check',
  'h' => 'hopefully',
  'i' => 'it', 'is',
  'w' => 'works',
  'a' => 'and',
  'f' => 'fine'
}

I'm trying to figure out what can I do to achieve the expected result. Are there any suggestions?

CodePudding user response:

The value should be an array of words. Check if the map entry exists. If it does, push onto it, otherwise create it.

function sortToMap(str) {
  let lowerString = str.toLowerCase();
  let result = lowerString.split(" ");
  let myMap = new Map();

  for (let i = 0; i < result.length; i  ) {
    let initial = result[i][0];
    if (myMap.has(initial)) {
      if (!myMap.get(initial).includes(result[i])) {
        myMap.get(initial).push(result[i]);
      }
    } else {
      myMap.set(initial, [result[i]]);
    }
  }
  return myMap;
}

let myString = "Test string to check How it Works and hopefully it is fine";
console.log(Object.fromEntries(sortToMap(myString)));

CodePudding user response:

Instead of setting the word as the value, you should create an array that stores all the words starting with a given letter.

Here is a working code :

function sortToMap(str) {
   const words = str.toLowerCase().split(" ")
   // no need for map in JS, an object will work fine
   const map = {}
   for(let word of words) {
      const key = word[0]
      if(!(key in map))
         map[key] = []
      map[key].push(word)
   }
   
   return map
}

let myString = "Test string to check How it Works and hopefully it is fine";
console.log(sortToMap(myString));

  • Related