如何在数组中查找对象的总和

时间:2016-12-09 16:36:48

标签: javascript

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

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

$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
            }
        ]
    }
]

3 个答案:

答案 0 :(得分:2)

这是使用Javscript reducefilter函数的理想选择。

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函数之后有的起始值。忘记把它放在那里很容易。

答案 1 :(得分:1)

你可以这样做:



var 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}]}],
    getTotalMinutes = function (time) {
      return time
        .map(function (s) {
          return s.minutes;
        })
        .reduce(function (a, b) {
          return a + b;
        }, 0);
    },
    result = students.map(function (student) {
      return {
        [student.name]: getTotalMinutes(student.time)
      };
    });

console.log(result);




答案 2 :(得分:1)

您可以使用students.reduce制作一系列主题,其中包含每个主题的总和:



var 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
    }]
}]

var subjectTimes = students.reduce(function(result, student) {
    student.time.reduce(function(prev, time) {
        if (time.subject in result)
            result[time.subject] += time.minutes;
        else
            result[time.subject] = time.minutes;
    }, {})
    return result;
}, {});

console.log(subjectTimes);