javascript - Sorting a JSON by value of a dynamic name property -


i've been trying online coding excericise, excercise :

a json array has random number objects contains key , double value. array may have 10000 objects. ex: = [{"a": 2.0},{"a": 2.7},{"c": 2.0},{"b": 5.1},{"d": 2.9},{"c": 2.0},{"f": 2.2},{"h": 2.1}]

another array b has random set of sum operations executed keys. value of keys can found in a. if key not presented in a, value zero. ex: b = ["a+b","b+d+f","k+z"]

your job combine arrays b , a, providing array c contains results of sum operations of b. resulting array must sorted in descending order. combining examples above, resulting array be: ex: c = [ {"b+d+f": 10.2}, {"a+b": 9.8}, {"k+z": 0} ]

the code looks (please let me know if there better implementation whit smaller o())

var = [{"a": 2.0},{"a": 2.7},{"c": 2.0},{"b": 5.1},{"d": 2.9},{"c": 2.0},{"f": 2.2},{"h": 2.1}]  var b = ["a+b","b+d+f","k+z"];  var c = [];    function sumarrays(){	  	for (var sum in b){  		var keystosum = b[sum].split("+");  		var sumatory = 0;  		for(var key in keystosum){			  			for(var number in a){  				if(a[number].hasownproperty(keystosum[key])){  					sumatory += a[number][keystosum[key]];  				}  			}  		}    		c.push(json.parse("{\"" + b[sum] + "\":" + sumatory + "}"));  	}    	//c.sort(function(a,b){  	//	return a.value - b.value;  	//});  }

i can't array c sorted, because property name changes. ideas?

thanks !

first need first value of object:

function firstvalue(obj){    for(var prop in obj){       return obj[prop];    } } 

then use sort

a.sort(function(a,b){ return firstvalue(a)-firstvalue(b)}) 

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -