Write a function named sort_by_average_rating that takes a list/array of key-value stores as a parameter where each key-value store has keys ratings, budget, and box_office where budget and box_office are integers and ratings is a list of integers. Sort the input based on the average of the values in ratings.
I tried adding everything within a for loop when the key is equal to ["ratings"] then after that, I average the results from the two for loops. Lastly, I used a separate function to sort everything.
function key(a,b){
for(var i = 0; i < a.length; i++){
tol1 += a[i]["ratings"];
for(var x = 0; x < b.length; x++) {
tol2 += b[x]["ratings"];
}
var average = (tol1/tol2);
}
return average;
}
function key(x,y){
if (x[key] < x[key]) { return -1; }
if (y[key] > y[key]) { return 1; }
return 0;
}
function sort_by_average_rating(b){
b.sort(key)
}
Result:
[
{'box_office': 12574015, 'budget': 3986053.18, 'ratings': [8, 7, 1]},
{'box_office': 44855251, 'budget': 3301717.62, 'ratings': [7, 1, 1]},
{'box_office': 36625133, 'budget': 8678591, 'ratings': [7, 6, 2, 8]},
{'box_office': 48397691, 'budget': 15916122.88, 'ratings': [7, 3, 8, 8, 6, 8]},
{'box_office': 43344800, 'budget': 4373679.25, 'ratings': [1, 1, 7, 4]}
]
Expected:
[
{'box_office': 44855251, 'budget': 3301717.62, 'ratings': [7, 1, 1]},
{'box_office': 43344800, 'budget': 4373679.25, 'ratings': [1, 1, 7, 4]},
{'box_office': 12574015, 'budget': 3986053.18, 'ratings': [8, 7, 1]},
{'box_office': 36625133, 'budget': 8678591.0, 'ratings': [7, 6, 2, 8]},
{'box_office': 48397691, 'budget': 15916122.88, 'ratings': [7, 3, 8, 8, 6, 8]}
]
function key(). Only the second definition is used, the first one is overwritten. Actually, that's just the tip of the iceberg...keyinside the function is still referring to the function itself.