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' ]
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…