0

I just started learning JavaScript, and ran into such a problem, I have a nested array, I want to summarize the price value of these arrays and return the existing sum, I wonder which method is applicable for it, which does not hurt the performance, I need one example to understand the way to solve the problem. Thanks in advance

const initialData = [
      {
          title: 'm2212',
          data: [
              {
                  id: 98233181232,
                  variations:[{
                          warranty: '',
                          price: 120,
                          comment: '',
                      }]
  
              },
          ]
      },
      {
          title: 'm2',
          data: [
              {
                  id: 982812,
                  variations:[{
                          warranty: '',
                          price: 92,
                          comment: '',
                      }]
  
              },
               {
                  id: 92182812,
                  variations:[{
                          warranty: '',
                          price: 922,
                          comment: '',
                      }]
  
              },
          ]
      },
 ]
 
 
 
 //what i tried
 let sum = 0
 initialData.forEach((el)=>{
   el.data.forEach((el1)=>{
     sum = sum + el1.variations[0].price
    })
 })

 console.log(sum);
Taghi Khavari
  • 6,272
  • 3
  • 15
  • 32
Nightcrawler
  • 943
  • 1
  • 11
  • 32
  • Write a double loop, loop through `initialData` first, loop through `data` array next then through `variations` array. Keep on adding `variations` value to a variable. This will give the sum. – Nitheesh Feb 09 '22 at 11:55
  • 1
    Does this answer your question? [Better way to sum a property value in an array](https://stackoverflow.com/questions/23247859/better-way-to-sum-a-property-value-in-an-array) – Nitheesh Feb 09 '22 at 11:57

3 Answers3

2

Your data structure looks pretty simple, so I'll just explain in plain english how to accomplish it:

The simple straight forward way is to ignore all the fancy functional things you can do on arrays, and just do this:

Set a sum variable equal to 0. Iterate over every element of initialData. On each element, iterate over every element of data. On each data element, iterate over every element of variations. Add the price property to your sum variable.

TKoL
  • 13,158
  • 3
  • 39
  • 73
1

The simplest and performant approach would be something like this code:

  const sum = initialData.reduce((sum, item) => {
    const itemSum = item.data.reduce((dataSum, dataItem) => {
      const itemDataSum = dataItem.variations.reduce((variantsSum, variantItem) => {
        return variantsSum + variantItem.price;
      }, 0);

      return dataSum + itemDataSum;
    }, 0);
    return sum + itemSum;
  }, 0);

  const initialData = [
    {
      title: "m2212",
      data: [
        {
          id: 98233181232,
          variations: [
            {
              warranty: "",
              price: 120,
              comment: ""
            }
          ]
        }
      ]
    },
    {
      title: "m2",
      data: [
        {
          id: 982812,
          variations: [
            {
              warranty: "",
              price: 92,
              comment: ""
            }
          ]
        },
        {
          id: 92182812,
          variations: [
            {
              warranty: "",
              price: 922,
              comment: ""
            }
          ]
        }
      ]
    }
  ];

  const sum = initialData.reduce((sum, item) => {
    const itemSum = item.data.reduce((dataSum, dataItem) => {
      const itemDataSum = dataItem.variations.reduce((variantsSum, variantItem) => {
        return variantsSum + variantItem.price;
      }, 0);

      return dataSum + itemDataSum;
    }, 0);
    return sum + itemSum;
  }, 0);

  console.log(sum);
Taghi Khavari
  • 6,272
  • 3
  • 15
  • 32
  • Thousands of duplicate, no proper attempts, still this question needs to be answered? Please raise a vote this close this question. – Nitheesh Feb 09 '22 at 11:58
1

You could add some checks for having an array or object and if so iterate the values.

This approach does not need to know the structure of the data, it takes breadth-first search for finding the wanted key.

const
    sum = (value, key) => {
        if (!value || typeof value !== 'object') return 0;
        if (Array.isArray(value)) return value.reduce((t, o) => t + sum(o, key), 0);
        if (key in value) return value[key];
        return sum(Object.values(value), key);
    },
    data = [{ title: 'm2212', data: [{ id: 98233181232, variations: [{ warranty: '', price: 120, comment: '' }] }] }, { title: 'm2', data: [{ id: 982812, variations: [{ warranty: '', price: 92, comment: '' }] }, { id: 92182812, variations: [{ warranty: '', price: 922, comment: '' }] }] }];

console.log(sum(data, 'price'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Thousands of duplicate, no proper attempts, still this question needs to be answered? Please raise a vote this close this question. – Nitheesh Feb 09 '22 at 11:58