Menu

gitpiper

weightedAverage javascript Code Snippet in 2024

mathintermediate

Last Updated: 20 April 2024

Calculates the weighted average of two or more numbers.

  • Use Array.prototype.reduce() to create the weighted sum of the values and the sum of the weights.
  • Divide them with each other to get the weighted average.
const weightedAverage = (nums, weights) => { const [sum, weightSum] = weights.reduce( (acc, w, i) => { acc[0] = acc[0] + nums[i] * w; acc[1] = acc[1] + w; return acc; }, [0, 0] ); return sum / weightSum; };
weightedAverage([1, 2, 3], [0.6, 0.2, 0.3]); // 1.72727

javascript snippet similar to weightedAverage For You in April 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️