The answer is to take the median. One of the properties of the median is that it minimizes the L1 distance to each element. (To make sense of the Wikipedia article, take the probability distribution to be the uniform distribution over your original series of numbers).
This is the algorithm which solves the problem (originally written by dc2dc2):
function median(arr) {
arr.sort(function(a, b) { return a - b; });
var half = floor(arr.length/2);
if ( arr.length % 2 ) {
return arr[half];
} else {
return (arr[half-1] + arr[half]) / 2.0;
}
}
function minl1(arr) {
var moves = 0;
var mdn = median(arr);
for ( var i = 0; i < arr.length; ++i ) {
moves += Math.abs(mdn - arr[i]);
}
return moves;
}
minl1([3, 1, 1, 1]); // -> 2