0

I have array of data which has array inside of it, in second array i need to sum one column and get the result back.

Screenshot

one

Code

controller

public function index()
{
  $zones = ZoneRegion::orderby('id', 'desc')->with(['areas', 'segments', 'links', 'cabels'])->get();
  return response()->json([
    'data' => $zones,
    'message' => 'Zona Wilayah berhasil diambil.'
  ]);
}

component

data() {
    return {
        regions: [],
    }
},
methods: {
    fetchRegions() {
        axios
        .get('/api/admin/zones', {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('access_token')
            }
        })
        .then(response => {
            this.regions = response.data.data;
        })
        .catch(function (error) {
            console.log('error', error);
        });
    },
}

Any suggestion?

mafortis
  • 6,750
  • 23
  • 130
  • 288
  • I posted an answer, but now I believe that you only want to sum cable lengths for each row in your data array? Or do you want total length of all rows together? – Robert Kujawa Apr 15 '20 at 03:45
  • Let me know what you need so I can update my answer, the reduce method shall be used either way. – Robert Kujawa Apr 15 '20 at 03:47
  • @RobertKujawa thank you, yes i only need sum for each row. i'll try your code and let you know – mafortis Apr 15 '20 at 03:50

1 Answers1

1

You can use the js reduce method to sum all the cable lengths together.

data() {
    return {
        regions: []
    }
},
methods: {
    fetchRegions() {
        axios
        .get('/api/admin/zones', {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('access_token')
            }
        })
        .then(response => {
            this.regions = response.data.data.map(region => ({
                ...region,
                totalCableLength: region.links.reduce((total, link) => {
                    return total + parseInt(link.cable_length);
                }, 0)
            }));
        })
        .catch(function (error) {
            console.log('error', error);
        });
    }
}

This will save your regions just like you retrieved them from the server, but it will add the sum of all the links cable length to each region, it will be keyed by 'totalCableLength'.

Robert Kujawa
  • 967
  • 6
  • 21
  • Hi, I've tried your code in component it does return the result but as i need to use it in my table it shows nothing (you know tables are looped, so i think this `getCableLength(data)` somehow should be pushed to `this.regions` maybe?) – mafortis Apr 15 '20 at 03:56
  • i think your code sum all values at once, what i'm looking for is row based so let say (row 1 = 1000 & row 2 = 1500) but what i get now is total 2500 – mafortis Apr 15 '20 at 03:58
  • I updated my answer, so you can retrieve your total simply by looping through your regions array and accessing `region.totalCableLength`. – Robert Kujawa Apr 15 '20 at 03:58
  • Sorry, my bad, remove the semicolon. I update my answer again. – Robert Kujawa Apr 15 '20 at 04:02
  • should be `}, 0) }));` less 1 `)` before `;` – mafortis Apr 15 '20 at 04:04
  • variable isn't exist in my regions array https://ibb.co/wdf8mzv – mafortis Apr 15 '20 at 04:07
  • It won't be in the response you get from Laravel, It will be on the Vue side. inside the regions array, in each region. Do you have vue devtools plugin installed? – Robert Kujawa Apr 15 '20 at 04:09
  • Check the regions array in vue devtools each region will now have a property called totalCableLength with the sum of all links. – Robert Kujawa Apr 15 '20 at 04:12
  • yes in here exist https://ibb.co/6RJhfQ0 but not printing in table – mafortis Apr 15 '20 at 04:12
  • Show me your vue template code, how are you printing it? Are you using `v-for` ? – Robert Kujawa Apr 15 '20 at 04:13
  • it was misspelling in my table, my apologize, is there any way to add thousands comma into this numbers? – mafortis Apr 15 '20 at 04:14
  • You can check out [this](https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript) to add commas each thousand – Robert Kujawa Apr 15 '20 at 04:16