function fn(c) { var d = {}; return c.slice().sort(function(a, b) { return a - b }).map(function(a) { var b = d[a] || 0, b = c.indexOf(a, b); d[a] = b + 1; return b }) }; alert(fn([3, 1, 2])) alert(fn([3, 3, 1, 2]))