Sum of array object property values in new array of objects in Javascript

前端 未结 5 982
时光取名叫无心
时光取名叫无心 2020-11-27 23:41

I have an array of objects where i need sum of object property values in new array of objects,

Input:

var inputArray = [
  { subject: \'Maths\', mark         


        
5条回答
  •  一个人的身影
    2020-11-28 00:33

    Here you go:

    function convert(inputArray) {
        var temp = {};
        for(var i = 0; i < inputArray.length; i++) {
            var subject = inputArray[i].subject;
    
            // check if there is already an entry with this subject in the temp array
            if(temp.hasOwnProperty(subject)) {
                // if it is already in the list, add the marks and the noOfStudents
                temp[subject].marks = temp[subject].marks + parseInt(inputArray[i].marks, 10);
                temp[subject].noOfStudents = temp[subject].noOfStudents + parseInt(inputArray[i].noOfStudents, 10);
            }
            else {
                // if it is not yet in the list, add a new object
                temp[subject] = {
                    subject: subject,
                    marks: parseInt(inputArray[i].marks, 10),
                    noOfStudents: parseInt(inputArray[i].noOfStudents, 10)
                }
            }
        }
    
        // the temporary array is based on the subject, you are however interested on the effective value object
        var result = [];
        for(var entryKey in temp) {
            result.push(temp[entryKey]);
        }
    
        return result;
    }
    

提交回复
热议问题