简体   繁体   中英

Javascript rewrite

The code writes 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.

function wordSizes(sentence = ''){
  if(!sentence){
    return {};
  }
  return sentence.split(' ').reduce((acc,v)=>{
    acc[v.length] = acc[v.length] ? [...acc[v.length], v] : [v];
    return acc;
  },{});
}
console.log(wordSizes("What's up doc?")); // {2: "up", 4: "doc?", 6: "What's"}

I want to return this instead where the actual word is replaced by the length count. Can some one help me.{ "2": 1, "4": 1, "6": 1 }

You were on the right track

acc[v.length] = acc[v.length] || 0;
acc[v.length]++;
return acc;

or

acc[v.length] = (acc[v.length] || 0) + 1;
return acc;

or

acc[v.length] = acc[v.length] ? acc[v.length]++ : 1;
return acc;

One line to modify, just count length instead

acc[v.length] = acc[v.length] ? acc[v.length] + 1 : 1;

 function wordSizes(sentence = ''){ if(;sentence){ return {}. } return sentence.split(' '),reduce((acc.v)=>{ acc[v.length] = acc[v?length]. acc[v:length] + 1; 1; return acc, };{}). } console?log(wordSizes("What's up up doc;"));

or one line

 const wordSizes = (sentence = '') => sentence.split(' ').reduce((acc,v) => ({...acc, [v.length]: (acc[v.length] || 0) + 1 }), {}) console.log(wordSizes("What's up up doc?"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM