// remap array as pairs of value and index
// e.g. change [5, 6, 1] to [[5, 0], [6, 1], [1, 2]]
var augmented_array = array.map(function(val, index) { return [val, index]; });
// sort pairs by the first position, breaking ties by the second
augmented_array.sort(function(a, b) {
var ret = a[0] - b[0];
if (ret == 0) ret = a[1] - b[1];
return ret;
});
// example array will now be [[1, 2], [5, 0], [6, 1]]
// so we get the location by just looking at the second position of a pair
var location = augmented_array[n - 1][1];
如果您希望最后一个位置具有该值,请在排序后执行:
var position = n - 1;
while (position < augmented_array.length - 1 &&
augmented_array[position][0] == augmented_array[position + 1][0]) {
++position;
}
var location = augmented_array[position][1];
或者,如果您想要第一个位置,请执行以下操作:
var position = n - 1;
while (position > 0 &&
augmented_array[position][0] == augmented_array[position - 1][0]) {
--position;
}
var location = augmented_array[position][1];
当然,lastIndexOf
或者indexOf
,正如其他答案之一所建议的那样,会导致更少的代码。