gpt-3.5-turbo-0125· OpenAI
WildChat-4.8M (AI2)
javascript find average of groupped data in array - const modDat = [ { "Variable":…
- User
javascript find average of groupped data in array - const modDat = [ { "Variable": "Trimmed Can Height", "Value": "1" }, { "Variable": "Trimmed Can Height", "Value": "165" }, { "Variable": "Wtf", "Value": "10" }, { "Variable": "zxc", "Value": "10" }, { "Variable": "zxc", "Value": "10" }, { "Variable": "zxc", "Value": "10" } ]
- Assistant
To find the average of grouped data in the given array, you can use the following JavaScript code:
const modDat = [ { "Variable": "Trimmed Can Height", "Value": "1" }, { "Variable": "Trimmed Can Height", "Value": "165" }, { "Variable": "Wtf", "Value": "10" }, { "Variable": "zxc", "Value": "10" }, { "Variable": "zxc", "Value": "10" }, { "Variable": "zxc", "Value": "10" } ]; const groupedData = modDat.reduce((acc, obj) => { acc[obj.Variable] = acc[obj.Variable] || {sum: 0, count: 0}; acc[obj.Variable].sum += parseInt(obj.Value); acc[obj.Variable].count++; return acc; }, {}); const averageData = {}; for (let key in groupedData) { const average = groupedData[key].sum / groupedData[key].count; averageData[key] = average; } console.log(averageData);This code creates a grouped data object using the
reducefunction, then calculates the average for each group using afor...inloop. Finally, it logs the average data to the console.