javascript - Array of String to an array of JSON objects -


for example:

var array = ['a','a','b','b','c','c','c','c','d','d','d','d','d','d'];  var ans = array.reduce(function(acc,curr){     if(typeof acc[curr] == 'undefined') {         acc[curr] = 1;        } else {         acc[curr] += 1;     }      return acc; }, {}); 

will give me:

ans = {'a':'2','b':'2','c':'4','d':'6'} 

but goal in format

ans = [{'word':'a','count':'2'},{'word':'b','count':'2'},{'word':'c','count':'4'},{'word':'d','count':'6'}] 

any appreciated thanks.

you have concise data format however, if must transform more verbose version, try

var wordcount = []; object.keys(ans).foreach(function(word) {     wordcount.push({         word: word,         count: ans[word]     }); }); 

if wanted all-in-one solution, try one...

var array = ['a','a','b','b','c','c','c','c','d','d','d','d','d','d'];  var ans = array.map(function(word) {     return { word: word, count: 1 }; }).reduce(function(p, c) {     (var = 0, l = p.length; < l; i++) {         if (p[i].word === c.word) {             p[i].count += c.count;             return p;         }     }     p.push(c);     return p; }, []); 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -