[Vuejs]-Take the average of an array items

0👍

avgArray: function(){
    const sum = arr => arr.reduce((a,c) => (a += c),0); // add equals and init with 0
    const avg = arr => sum(arr) / arr.length;
    this.myArray = this.estates.map(a =>  a.m2_price)
    console.log(avg(this.myArray));
}

You were setting this.myArray as a value and not an array. You could’ve either pushed the m2_price or map it like above

Reduce function only exists on arrays. Clearly you were logging this.myArray and getting integers. Hence the error.

-1👍

That is what reduce is for

const average = array => (array && array.length) ? (array.reduce((sum, item) => sum + item, 0) / array.length) : undefined;


console.log(average([1,2,3,4,5,6]));

export the average function from a file called average.js

Applied to your situation

import { average } from 'pathToYourIncludeLibrary/average';

data() {
    return {
        myArray:[],
    }
},    
methods: {
    avgArray: () => average(this.myArray)
}

Leave a comment