d3 / d3-array

Array manipulation, ordering, searching, summarizing, etc.

Home Page:https://d3js.org/d3-array

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

mode?

mbostock opened this issue · comments

Something like:

function mode(values, f) {
  const m = new InternMap();
  let greatest;
  let greatestCount = 0;
  for (const v of Array.from(values, f)) {
    const count = (m.get(v) || 0) + 1;
    if (count > greatestCount) greatestCount = count, greatest = v;
    m.set(v, count);
  }
  return greatest;
}

A bit faster than d3.groupSort(values, v => v.length, f).pop()?

It could also be written as…

function mode(values, f = identity) {
  const g = greatest(group(values, f), ([, group]) => group.length);
  return g && g[0];
}