gpt4 book ai didi

javascript - 如何找到数组中对象的总和

转载 作者:行者123 更新时间:2023-11-29 17:53:45 25 4
gpt4 key购买 nike

我有这个对象数组,我想根据某些条件计算学生在特定科目上花费的时间。

我有这段代码来识别主题:但我很难找到这些特定主题的分钟总和。

$scope.total = 0;
$scope.found = [];

angular.forEach($scope.all, function(value, index) {
angular.forEach(value.time, function (item, index) {

$scope.total += value.time[index].minutes;

if (item.subject === "english" || item.subject === "maths"
&& $scope.total === 150) {
$scope.found.push(value);
}
});
});
"students": [
{
"id": 1,
"name": "Natalie",
"gender": "female",
"time": [
{
"subject": "geography",
"minutes": 100
},{
"subject": "english",
"minutes": 20
},{
"subject": "maths",
"minutes": 760
}
]
},{
"id": 2,
"name": "John",
"gender": "male",
"time": [
{
"subject": "spanish",
"minutes": 450
},{
"subject": "maths",
"minutes": 900
},{
"subject": "geography",
"minutes": 200
}
]
}
]

最佳答案

这是使用 Javscript reduce 的一个很好的候选者和 filter功能。

Filter 将针对数组中的每个条目运行一个函数,返回一个新数组,其中仅包含该函数返回 true 的值。

Reduce 将在遍历数组中的每个条目时保留总值。您可以说它用于将数组“缩减”为单个值,这正是我们在这里要做的。

这是一个示例,假定 students 变量包含您的学生数组:

// We'll match against this variable
var desiredSubject = "maths"

// First, we iterate over each student in the array
var time = students.reduce(function(previousTime, student) {
// Inside the array is another array, so we want to
// reduce that one after filtering it to match our subject
var subjectTime = student.time.filter(function(subject) {
// Keep only subjects that match ours
return subject.subject == desiredSubject;
}).reduce(function(previousMinutes, subject) {
// Then sum up the minutes from each one
return previousMinutes + subject.minutes;
}, 0); // Our initial sum is 0
// Sum up each student's minutes
return previousTime + subjectTime;
}, 0); // Again, with an initial sum of 0

请记住,reduce 函数的一个常见“陷阱”是您在 reduce 函数之后有起始值。很容易忘记把它放在那里。

关于javascript - 如何找到数组中对象的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41064980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com