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
Wonderful and quick reply. Fresh, smart, and surprising, too. Thanks.
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.