Dev Helpers
← Back

Choose a weighted median

Choose a weighted median using JavaScript.

Open this example in the interactive library

Source code

const rows = [
  [1, 2],
  [5, 5],
  [9, 1],
].toSorted((a, b) => a[0] - b[0]);
const half = rows.reduce((s, [, w]) => s + w, 0) / 2;
let running = 0;
console.log(rows.find(([, w]) => (running += w) >= half)[0]);

Sample output

5