Interquartile Mean (IQM)

Where can I find javascript to obtain the interquartile mean of an array of numbers?

Hereâ€™s a modification of an implementation from the â€ścode golfâ€ť stackexchange:

``````function IQM (arr) {
const l = arr.length;
return arr.concat(arr,arr,arr)
.sort((x,y) => x-y)
.slice(l, -l)
.reduce((a,v) => a+v, 0)/(2*l);
}
``````

The idea is to concatenate 3 copies of the original array `arr` so that one has a â€śquadruplicatedâ€ť array. Then one sorts and slices to get (a quadruplication of) the middle quartiles (an array of length `2*l`, where `l=arr.length`). Finally, one computes the mean.

Hereâ€™s Neilâ€™s original code:

``````a=>a.concat(a,a,a).sort(g=(x,y)=>x-y).slice(l=a.length,-l).reduce(g,0)/l/-2
``````
2 Likes

Wonderful and quick reply. Fresh, smart, and surprising, too. Thanks.

There is also a package available on npm: compute-midmean.

In the unlikely case it matters, note that this npm package treats arrays with lengths not divisible by 4 in a different way than the code I copied from stackexchange does.

The latter calculation gives fractional weights to â€śin-betweenâ€ť values as is done on Wikipedia, whereas `compute-midmean` gives them a full weight (which follows the paper that they cite).

Thanks! For now, the one-liner suffices, and I find it quite elegant (despite the array quadruplication).

The difference in calculation does not make much difference for me. I just want to strip any outliers from the set.