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

前端 未结 5 977
时光取名叫无心
时光取名叫无心 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:34

    You can use forEach() to iterate and generate the new array

    var inputArray = [
      { subject: 'Maths', marks: '40', noOfStudents: '5' },
      { subject: 'Science', marks: '50', noOfStudents: '16' },
      { subject: 'History', marks: '35', noOfStudents: '23' },
      { subject: 'Science', marks: '65', noOfStudents: '2' },
      { subject: 'Maths', marks: '30', noOfStudents: '12' },
      { subject: 'History', marks: '55', noOfStudents: '20' }
    ],
        res = [],
        key = {};
    
    inputArray.forEach(function(v) {
      if (key.hasOwnProperty(v.subject)) { // check subject already added by using key object
        res[key[v.subject]].marks += Number(v.marks); //incase already exist parse number and add
        res[key[v.subject]].noOfStudents += Number(v.noOfStudents);
      } else {
        key[v.subject] = res.length; // create index entry in key object
        res.push({ // push the value 
          'subject': v.subject,
          'marks': Number(v.marks),
          'noOfStudents': Number(v.noOfStudents)
        })
        // if you pushed the original object then the original array also will get updated while adding the mark, so never push the refernce
      }
    })
    
    console.log(res);


    Using reduce() method

    var inputArray = [
      { subject: 'Maths', marks: '40', noOfStudents: '5' },
      { subject: 'Science', marks: '50', noOfStudents: '16' },
      { subject: 'History', marks: '35', noOfStudents: '23' },
      { subject: 'Science', marks: '65', noOfStudents: '2' },
      { subject: 'Maths', marks: '30', noOfStudents: '12' },
      { subject: 'History', marks: '55', noOfStudents: '20' }
    ],
        key = {};
    
    res=inputArray.reduce(function(arr,v) {
      if (key.hasOwnProperty(v.subject)) { // check subject already added by using key object
        arr[key[v.subject]].marks += Number(v.marks); //incase already exist parse number and add
        arr[key[v.subject]].noOfStudents += Number(v.noOfStudents);
      } else {
        key[v.subject] = arr.length; // create index entry in key object
        arr.push({ // push the value 
          'subject': v.subject,
          'marks': Number(v.marks),
          'noOfStudents': Number(v.noOfStudents)
        })
        // if you pushed the original object then the original array also will get updated while adding the mark, so never push the refernce     
      }
      return arr;
    },[])
    
    console.log(res);


    FYI : You can avoid the key object by using find() method, but performance wise that may be little bit slower.

提交回复
热议问题