How to get the average from array of objects
Despite of having several answers I would like to add mine focusing to improve the code quality:
- You can use destructuring in
forEach()
to just get thefood
property of the object as that is only the property you are interested with. - Despite of dividing inside loop we can have only one division operation after the loop is completed. This saves a lot of computation when the array is huge(thousands of objects)
- You can use short hand like
+=
in the loop for summing up the value. - You can make a single line code in
forEach()
const ratings = [ {food:3}, {food:4}, {food:5}, {food:2}];
let foodTotal = 0;let length = ratings.length;ratings.forEach(({food})=> foodTotal += food);
console.log("FOOD",foodTotal/length);
Calculate average of an array with objects that has a nested Object
There are two simple steps to the problem.
First, you need to reduce the array to an object with years and values:
// this outputs
// { 2017: [8, 5], 2018: [9], 2019: [7] }
function byYear(array) {
// take each item of an array
return array.reduce((acc, data) => {
// take the values of that item
Object.entries(data.values).forEach(([year, value]) => {
// and map all the values to years
acc[year] = acc[year] || []
acc[year].push(value)
})
return acc
}, {})
}
The second step is just taking averages:
function average(object) {
const averages = {}
for (let key in object) {
averages[key] = object[key].reduce((sum, value) => sum + value) / object[key].length
}
return averages
}
And now you put them together:
average(byYear(input))
In here, the input
is the filtered array. As a whole snippet:
function byYear(array) {
return array.reduce((acc, data) => {
Object.entries(data.values).forEach(([year, value]) => {
acc[year] = acc[year] || []
acc[year].push(value)
})
return acc
}, {})
}
function average(object) {
const averages = {}
for (let key in object) {
averages[key] = object[key].reduce((sum, value) => sum + value) / object[key].length
}
return averages
}
const output = average(byYear([{
course: "math",
id: 4,
values: {
2017: 8,
2018: 9
}
}, {
course: "math",
id: 4,
values: {
2017: 5,
2019: 7
}
}]))
console.log(output)
calculate sum, average array of object in js use reduce or for loop
You can reduce
to combine age values per group, then map
to compute averages per key and convert back to an object with Object.fromEntries
:
const users = [
{ group: 'editor', name: 'Adam', age: 23 },
{ group: 'editor', name: 'John', age: 28 },
{ group: 'editor', name: 'William', age: 34 },
{ group: 'admin', name: 'Oliver', age: 28 }
];
const grouped = users.reduce((a, e) => {
if (!a[e.group]) {
a[e.group] = [];
}
a[e.group].push(e.age);
return a;
}, {});
const avgs = Object.fromEntries(
Object.entries(grouped).map(([k, v]) => [
k, v.reduce((a, e) => a + e, 0) / v.length
])
);
console.log(avgs);
Average of array inside an object
If you are looking for traditional loop:
const Students = [{
name: 'Bob',
marks: [78, 80, 89, 90, 68],
},
{
name: 'Alin',
marks: [87, 60, 59, 70, 68],
},
{
name: 'bikash',
marks: [82, 60, 79, 60, 80],
},
];
var average;
for (let i = 0; i < Students.length; i++){
var marks = Students[i]["marks"];
var total = 0;
console.log(marks);
for (var j = 0; j < marks.length; j++ ) {
total += marks[j];
}
average = total / marks.length;
// answer for question in the comment
var msg = Students[i]["name"] + " has average mark: " + average;
console.log(msg)
}
console.log(average)
Find the average of an array with objects (Java)
Reason for error Array type expected, java.lang.Object"
is belowline
`total = total + GeometricShape[i];
maybe you need to change it to
total = total + shapes[i];
Calculate average of value in array of object
You can easily achieve this using reduce
. Add all readingTime
and divide it by the length
of the readingTime
.
readingTime
is property of an object and it is not an array.
You can only use reduce
on Array.
You need to divide the total(addition of readingTime) with BookDetails.length
const BookDetails = [{
bookName: "Harry Pottar",
readingTime: 10663
},
{
bookName: "Harry Pottar",
readingTime: 10986
},
{
bookName: "kaptura Tech",
readingTime: 7034
},
];
const result =
BookDetails.reduce((acc, curr) => acc + curr.readingTime, 0) /
BookDetails.length;
console.log(result);
Most efficient way to get average by object property (array of Objects)
Looks like this is similar to the answer you posted yourself, except I separated out the averaging of the Map into its own step.
const data = [[{ SYD393: 3 }, { STA244: 4 }, { STA255: 5 }, { CSE255: 4 }, { ASD323: 5 },], [{ ASD323: 5 }, { STA255: 5 }, { SYD393: 1 },],];
const avg = a => a.reduce((a, b) => a + b, 0) / a.length,
sums = data.flat().reduce((a, o) => {
const [[c, r]] = Object.entries(o);
a.set(c, (a.get(c) ?? []).concat(r));
return a;
}, new Map),
avgs = new Map([...sums.entries()].map(([c, rs]) => [c, avg(rs)])),
res = data.map(us => us.map(o => {
const [k] = Object.keys(o); return { [k]: avgs.get(k) }
}));
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Related Topics
How to Get Route Url Params in a Page in Nuxt2 and 3
Check If a Key Exists Inside a Json Object
How to Pass Input Value into a Function on Form Submit in Angular 6
Text Input Allow Only Integer Input in Angularjs
Call Method That Inside Another Component - React Js
Deleting Nested Property in JavaScript Object
Nested Json: How to Add (Push) New Items to an Object
How to Move the Mouse Pointer and Click With Selenium Webdriver JavaScript
Sum of Numbers in an Array With JavaScript
Filter on Multiple Columns Using One Pipe Angular 2
How to Change Background Color of a Row on Checkbox Selection
How to Toggle Class to a Div Element in Reactjs
Pass Variable from Android to JavaScript Launched in Webview
Export Method/Function in React Native
Display Data Label (Legend) in Line-Chart Using Chartjs
How to Make Mongoose Not Insert Empty Array or Object Fields into a Document
Callback Function Cannot Access Variable Within Parent Function'S Scope