var findMaxAverage = function (nums, k) { var max = 0; while (nums.length >= k) { a = nums.slice(0, k); n = sum(nums.slice(0, k)); console.log(n); if (n > max) { max = n; } nums.shift(); } return max / k; }; function sum(arr) { var s = 0; arr.forEach(function (val, idx, arr) { s += val; }, 0); return s; } console.log(findMaxAverage([1, 12, -5, -6, 50, 3], 4));