Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

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 
question from:https://stackoverflow.com/questions/65856711/count-word-length-with-occurrence-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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' ]
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...