Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

212
Vistas
Looping nested arrays get the sum in JavaScript

I am working on a Javascript array where I need to loop the 2nd array in the main array and get the total sum of a value of a particular field. below is what my JSON looks like. here I need to loop Array and get the sum of ps_lessons.lesson_length_minutes I need the O/P as 118 (20 + 22 + 33 + 43)

[
    {
        "sort_id": 1,
        "category": "Introduction",
        "ps_lessons": [
            {
                "id": "48ca672b-aaca-473c-b54b-3cf699da848b",
                "sort_id": 1,
                "lesson_title": "Welcome to the course",
                "lesson_length_minutes": 20
            },
            {
                "id": "3f0f5715-a442-4262-ad32-6fb653df62c2",
                "sort_id": 2,
                "lesson_title": "What is React JS?",
                "lesson_length_minutes": 22
            }
        ]
    },
    {
        "sort_id": 2,
        "category": "Fundamentals",
        "ps_lessons": [
            {
                "id": "e28abd67-29a4-4bc9-a415-fb5db0aabfa9",
                "sort_id": 4,
                "lesson_title": "Fundamentals of React JS",
                "lesson_length_minutes": 33
            },
            {
                "id": "1d9668da-94e6-4085-bd89-176cc4e8e62d",
                "sort_id": 3,
                "lesson_title": "Fundamentals of JSX",
                "lesson_length_minutes": 43
            }
        ]
    }
]

I tried something like the below by using the array method map 2 times but it's not working. can anyone suggest how to do this?

const extract_mins_and_sum = (result) => {
  console.log('result', result);
     result.map((single_row) =>
      let sum = 0;
        single_row.ps_lessons.map((single_row_lesson) =>
    
         ( console.log(single_row_lesson.lesson_length_minutes);
          sum += single_row_lesson.lesson_length_minutes)
        )
      );
    };

Thanks Venk

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

The straightforward way is to loop through each element of the big array and get the sum by using a reduce function on each ps_lessons array.

const extract_mins_and_sum = (result) => {
    let sum = 0;
    result.forEach((elem) => {
        sum += elem.ps_lessons.reduce((acc, val) => acc + val.lesson_length_minutes, 0);
    });

    return sum;
}

Map is generally used to map an array to another array, but preserving metadata like array length, order etc. Reduce is generally used to, well, reduce an array to a single value, based on whatever logic you use in the callback function. On this example, reduce is used to transform an array into a sum of some numeric fields.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use reduce function to solve this

const data = [
  {
    sort_id: 1,
    category: "Introduction",
    ps_lessons: [
      {
        id: "48ca672b-aaca-473c-b54b-3cf699da848b",
        sort_id: 1,
        lesson_title: "Welcome to the course",
        lesson_length_minutes: 20,
      },
      {
        id: "3f0f5715-a442-4262-ad32-6fb653df62c2",
        sort_id: 2,
        lesson_title: "What is React JS?",
        lesson_length_minutes: 22,
      },
    ],
  },
  {
    sort_id: 2,
    category: "Fundamentals",
    ps_lessons: [
      {
        id: "e28abd67-29a4-4bc9-a415-fb5db0aabfa9",
        sort_id: 4,
        lesson_title: "Fundamentals of React JS",
        lesson_length_minutes: 33,
      },
      {
        id: "1d9668da-94e6-4085-bd89-176cc4e8e62d",
        sort_id: 3,
        lesson_title: "Fundamentals of JSX",
        lesson_length_minutes: 43,
      },
    ],
  },
];

const sumMinutes = (lessons) => {
  return lessons.reduce((acc, ps) => {
    return (acc + (ps.ps_lessons ? sumMinutes(ps.ps_lessons): ps.lesson_length_minutes));
  }, 0);
};

console.log(sumMinutes(data))

about 4 years ago · Juan Pablo Isaza Denunciar

0

You could use a solution using map and reduce extracting the value to an external variable like so:

const data = [
  {
    sort_id: 1,
    category: "Introduction",
    ps_lessons: [
      {
        id: "48ca672b-aaca-473c-b54b-3cf699da848b",
        sort_id: 1,
        lesson_title: "Welcome to the course",
        lesson_length_minutes: 20,
      },
      {
        id: "3f0f5715-a442-4262-ad32-6fb653df62c2",
        sort_id: 2,
        lesson_title: "What is React JS?",
        lesson_length_minutes: 22,
      },
    ],
  },
  {
    sort_id: 2,
    category: "Fundamentals",
    ps_lessons: [
      {
        id: "e28abd67-29a4-4bc9-a415-fb5db0aabfa9",
        sort_id: 4,
        lesson_title: "Fundamentals of React JS",
        lesson_length_minutes: 33,
      },
      {
        id: "1d9668da-94e6-4085-bd89-176cc4e8e62d",
        sort_id: 3,
        lesson_title: "Fundamentals of JSX",
        lesson_length_minutes: 43,
      },
    ],
  },
];

const sumMinutes = (lessons) => {
  return lessons.reduce((acc, ps) => {
    return (acc + (ps.ps_lessons ? sumMinutes(ps.ps_lessons): ps.lesson_length_minutes));
  }, 0);
};

console.log(sumMinutes(data))

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda