Practical guides, tutorials, and insights from years of building web and desktop applications. Check out code examples you can actually use!
Find average and median of arrays in Javascript
Find average and median of a given array in Javascript. Problem We are given an array that is hopefully comprised of numbers. Find average and median. Get average Calculate sum, length and use them to get the average. const arr = [3, 7, 2, 6, 5, 4, 9]; const sum = arr.reduce((sum, val) => (sum += val)); const len = arr.length; console.log("average: ", sum / len); // 5.142857142857143 Get median Sort array. Median formula is different depending on whether length of array is odd or even. Array length = odd => median is the average of the two middle numbers Array length = odd => pick the middle number as median const arrSort = arr.sort(); const mid = Math.ceil(len / 2); const median = len % 2 == 0 ? (arrSort[mid] + arrSort[mid - 1]) / 2 : arrSort[mid - 1]; console.log("median: ", median); // 5 One important pre-requisite Although the above arrangement works, it is always a good idea to filter out our arrays for undesired elements! ...