Search code examples
javascriptjavascript-objects

How to find the element count of an array using the Map object


I have a paragraph of words and would like to find the count of each word, specifically using JavaScript's Map object.

I understand that this can be achieved using the .get() and .set() methods, but I am not sure how to implement this.

Below is my code.

let paragraph = `Lorem ipsum donec nisi taciti et elit congue turpis, lobortis 
                 massa suscipit massa est a praesent metus egestas, conubia turpis 
                 in cursus libero pharetra praesent.
                 Per bibendum taciti sit taciti facilisis a bibendum nisl massa non 
                 aliquam sem auctor ipsum eros, massa sed cubilia porta primis 
                 felis elementum non fringilla conubia neque aenean urna.`

// Split the paragraph into an array of individual words.

let words = paragraph.match(/\w+/gi);

let map = new Map();

for (let i = 0; i < words.length; i++) {
  let word = words[i];
  map.set(word, 0);
  // Logic - if (map contains word) {
  // map.set(word, count += 1);
  // } else {
  // map.set(word, 1);
  // }
}

console.log(map);

Solution

  • Using Array#reduce with Map.

    For each iteration set the word in the map.

    a.get("Lorem") will return a number or undefined. The || handles if it's undefined. Then add 1.

    Map#set also returns the map object.

    const paragraph = `Lorem ipsum donec nisi taciti et elit congue turpis, lobortis massa suscipit massa est a praesent metus egestas, conubia turpis in cursus libero pharetra praesent.
    Per bibendum taciti sit taciti facilisis a bibendum nisl massa non aliquam sem auctor ipsum eros, massa sed cubilia porta primis felis elementum non fringilla conubia neque aenean urna.`
    
    const words = paragraph.match(/\w+/gi);
    
    const res = words.reduce((a,c)=>{
      return a.set(c, (a.get(c)||0) + 1);
    }, new Map());
    
    console.log([...res]);