Search code examples
javascriptword-countword-frequency

Count word length with occurrence javascript


Write a function that takes a string consisting of one or more space separated words, and returns an object that shows the number of words of different sizes. Words consist of any sequence of non-space characters.

This is what I have so far

  const strFrequency = function (stringArr) {
    return stringArr.reduce((count,num) => {
  count [num] = (count[num] || 0) + 1;
    return count;
  },
  {})
  }

  let names = ["Hello world it's a nice day"];

  console.log(strFrequency(names)); // { 'Hello world it\'s a nice day': 1 } I need help splitting the strings 

Solution

  • Process: Check if it is an invalid input then return blank object else process it by splitting it into words then adding into an array of the same length in state object. Hope this is what you were looking for!

    const str = "Hello world it's a nice day";
    
    function getOccurenceBasedOnLength(str = ''){
      if(!str){
        return {};
      }
      return str.split(' ').reduce((acc,v)=>{
        acc[v.length] = acc[v.length] ? [...acc[v.length], v] : [v];
        return acc;
      },{});
    }
    
    
    console.log(getOccurenceBasedOnLength(str));
    

    Output

    {
      '1': [ 'a' ],
      '3': [ 'day' ],
      '4': [ "it's", 'nice' ],
      '5': [ 'Hello', 'world' ]
    }