Search code examples
javascriptdictionarycase-insensitive

count of word occurrences in a list, case insensitive


What is the most professional way to obtain a case insensitive count of the distinct words contained in an array using plain javascript? I have done the first attempt myself but does not feel much professional.

I would like the result to be a Map


Solution

  • You can use Array.reduce to store each word as a property and the occurrence of each as the value.

    In the reducer function, check whether the letter (converted to lowercase) exists as a property. If not, set its value to 1. Otherwise, increment the property value.

    const arr = ["a", "A", "b", "B"]
    
    const result = arr.reduce((a,b) => {
      let c = b.toLowerCase();
      return a[c] = a[c] ? ++a[c] : 1, a;
    }, {})
    
    console.log(result)
    As a one liner: const result = arr.reduce((a,b) => (c = b.toLowerCase(), a[c] = a[c] ? ++a[c] : 1, a), {})

    To convert it to a Map, you can use Object.entries (sugged by @Théophile):

    const arr = ["a", "A", "b", "B"]
    
    const result = arr.reduce((a, b) => {
      let c = b.toLowerCase();
      return a[c] = a[c] ? ++a[c] : 1, a;
    }, {})
    
    const m = new Map(Object.entries(result))
    m.forEach((value, key) => console.log(key, ':', value))