I've been trying to do an online coding excericise, the excercise look like this :
A json array A has a random number objects that contains a key and a double value. The array A may have up to 10000 objects. Ex: A = [{"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 a random set of sum operations executed with the keys. The value of those keys can be found in A. If the key is not presented in A, so its value is zero. Ex: B = ["a+b","b+d+f","k+z"]
Your job is to combine the arrays B and A, providing an array C that contains the results of the sum operations of B. The resulting array must be sorted in a descending order. Combining the examples above, the resulting array would be: Ex: C = [ {"b+d+f": 10.2}, {"a+b": 9.8}, {"k+z": 0} ]
The code looks like this (please let me know if there is any better implementation whit a smaller O())
var a = [{"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 get the array C sorted, because the property name changes. Any ideas?
Thanks !