Taking average of values and pushing those into different object

I am having a little trouble about pushing items. I have a couple regions in my hand. So I need to take same region’s average price. I done that. No problem at that part. But after that I also need push regions to the object that I created in the data. So then I can use those…

export default {
    name:'average',
    data(){
        return{
            locations: {
                paris: "",
                london: "",
            },
        }
    },
    methods: {
        avgArray: function (region) {
             const sum = arr => arr.reduce((a,c) => (a += c),0);
             const avg = arr => sum(arr) / arr.length;

             return avg(region);
        },
    },
    computed: {
        api(){
            return this.$store.getters.loadRegions;
        },
        groupedPrices () {
        	return this.api.reduce((acc, obj) => {
                var key = obj.region;
                if (!acc[key]) {
                    acc[key] = [];
                }
                acc[key].push(obj.m2_price);
                return acc;
            }, {});
        },
        averagePrices () {
            Object.entries(this.groupedPrices)
                .forEach(([key, value]) => {
                    if (key == "paris") {
                        this.locations.paris.push({ [key]: Math.round(this.avgArray(value)) });
                    }
                    if (key == "london") {
                        this.locations.london.push({ [key]: Math.round(this.avgArray(value)) });
                    }
            });
            return this.locations;
        },
    },
}

So normally, the key is region’s name. So I am trying if the name matches, then push it. But in the vue dev console, this error displays:

averagePrices:"(error during evaluation)"

How can I achieve this? And if you need to know more detail, please ask.

Are your paris and london arrays?

1 Like

Was about to ask the same… what is the expected structure of groupedPrices?

yes london, paris is arrays… they are keeping the prices. So then I can take the average of the each regions with the avgArray function.

here it is ss. (don’t mind the japanese :slight_smile: ) those are regions…

59

and after I take averages of each regions… Then I want to push each regions to locations: {} that I created in the data() so then I can use those…

Your data should be.

locations: {
      paris: [],
      london: [],
},

oh, you are right, this fix solved it. thank you!