I recently had this question on a technical assessment. I've already turned in the assignment but I know I got the answer wrong. I'd love if someone could shed some light on this for me. The functions I wrote are below the question. When I tested them they did not work. Thanks for looking.
Consider the data structure below. We want to know the names of the individuals whose sales figures exceed $2000, and also the average sale amount for all the employees in the data structure. Please write the necessary code to produce this output in either Python or Javascript. Assume your runtime environment has a JSON parser and a print function available. Don’t be too concerned with the specifics of these functions or the output format. We are more interested in your logic than your syntax. Indicate any assumptions you make in your solution.
}
"Results": [
{
"Name": "Frank Jones",
"Department": "North America",
"Sales": 2500
},
{
"Name": "Sally Smith",
"Department": "North America",
"Sales": 2200
},
{
"Name": "Ed Kramer",
"Department": "Europe",
"Sales": 1700 },
{
"Name": "Susan Johnson",
"Department": "Asia",
"Sales": 2000
}
]
}
For sales higher than $2000
var sales = function(results) {
if (results.sales >= 2000) {
print(results.Name)
}
};
For average sales: I declared an empty array, used a for loop to push all results.sales into declared array. Used .reduce array method to get the total of all sales numbers, then divided by the array length to get they average sales number.
Function findAvg() {
let sales = [ ];
for (var i = 0; i < results.length; i++) {
sales.push(results[i].sales)
};
const reducer = (previousValue, currentValue) => previousValue + currentValue;
return sales.reduce(reducer)/sales.length
}