skip to Main Content

does anyone know how to compute inside grades? i tried use function but not working and i also try const grades = ‘grades’; but still not computing inside grades anyone know the algo of this?

  const students = [{
      name: 'Khelly',
      grades: [78, 92, 85, 88]
      },
      {
          name: 'Jared',
          grades: [90, 86, 94, 89]
      },
      {
          name: 'Alio',
          grades: [72, 84, 80, 76]
      },
      {
          name: 'Alvin',
          grades: [68, 72, 65, 80]
    }];
    
    
    const grades = 'grades';
    function calculateCar(array, property) {
      const total = array.reduce((accumulator, object) => {
        return accumulator + object[grades];
      }, 0)
      return total;
    }
    
    const totalCar = calculateCar(students, 'price');
    console.log(calculateCar);

2

Answers


  1. You need to use Array.reduce() for object[grades] in order to get total value

    BTW: property is useless in your code snippet,it’s a better way to pass property value via calculateCar parameters.

    const students = [{
      name: 'Khelly',
      grades: [78, 92, 85, 88]
      },
      {
          name: 'Jared',
          grades: [90, 86, 94, 89]
      },
      {
          name: 'Alio',
          grades: [72, 84, 80, 76]
      },
      {
          name: 'Alvin',
          grades: [68, 72, 65, 80]
    }];
    
    
    const grades = 'grades';
    function calculateCar(array, property) {
      const total = array.reduce((accumulator, object) => {
        return accumulator + object[grades].reduce((t, a) => t + a, 0);
      }, 0)
      return total;
    }
    
    const totalCar = calculateCar(students, 'price');
    console.log(totalCar);
    Login or Signup to reply.
  2. The OP mentioned the desired result as [ { name: 'Khelly', grades:95}, { name: 'Jared', grades: 87}, { name: 'Alio', grades: 83}, { name: 'Alvin', grades:82} ]. So just map the array and calculate sum of grades for each student:

    const students = [{
      name: 'Khelly',
      grades: [78, 92, 85, 88]
      },
      {
          name: 'Jared',
          grades: [90, 86, 94, 89]
      },
      {
          name: 'Alio',
          grades: [72, 84, 80, 76]
      },
      {
          name: 'Alvin',
          grades: [68, 72, 65, 80]
    }];
    
    const grades = students.map(({grades, ...student}) => ({...student, grades: grades.reduce((r, grade) => r + grade)}));
    
    console.log(grades);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search