javascript - How to find the max values from similar groups in an object -


i have object

obj = {  'ab-adf': 2,  'ab-d': 3,    'cd-23': 1,  'cd-df': 5,  'ef-a': 3,  'ef-nb': 4 }; 

expected output number or strings: 3, 5, 4 each ab, cd , ef group.

i looking solution print out ab-asdf=8, cd-ed=6 etc should keep original name '=' sign after it.

i know traditional way use loop , return max value.

var max = -infinity, x; for( x in obj) {     if( x.slice(0,2)==='ab' && obj[x] > max) max = obj[x];     if( x.slice(0,2)==='cd' && obj[x] > max) max = obj[x];     if( x.slice(0,2)==='ef' && obj[x] > max) max = obj[x];  //how return max value each group ? } 

first, javascript won't able interpret object because there special characters in keys. you'll need wrap keys in quotations this:

obj = {  'ab-xxx': 2,  'ab-yyy': 3,    'cd-xxx': 1,  'cd-yyy': 6,  'cd-zzz': 5,  'ef-xxx': 3,  'ef-yyy': 4, }; 

next, you'll want store max values each group, join max values string looking output.

// max values each prefix var max = {}; for(var key in obj) {   var prefix = key.slice(0,2);   if (max[prefix] === undefined || max[prefix] < obj[key]){     max[prefix] = obj[key];   } }  // concatenate max values string var maxstring = ''; for(key in max){   maxstring += max[key] + ' '; } maxstring = maxstring.trim(); 

edit:

yes, looking solution print out ab-asdf=8, cd-ed=6 etc should keep original name '=' sign after it.

to achieve output, can way:

// max values each prefix, , store max string var max = {}; for(var key in obj) {   var prefix = key.slice(0,2);   if (max[prefix] === undefined || +max[prefix].split('=')[1] < obj[key]){     max[prefix] = key + '=' + obj[key];   } }  // concatenate max values string var maxstring = ''; for(key in max){   maxstring += max[key] + ', '; } maxstring = maxstring.trim(); 

Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -