How do you find the 10 indexes of a javascript array that have the highest numeric values?
Solution 1:
You could get the indices and sort them by using the values and get the top wanted indices.
const
values = [7, 3, 4, 5, 2, 8],
indices = [...values.keys()].sort((a, b) => values[b] - values[a]);
console.log(indices.slice(0, 3));
Solution 2:
There might be other ways, but what comes to me off the top of my head is to map the original array to a set of value/index pairs, sort the result based on value, then grab the last (or first) 10 items of the sorted array (depending on whether or not you did an ascending or descending sort).
yourArray.map((value, index) => ({ value, index }))
.sort((a, b) => b.value - a.value)
.slice(0, 10)
.map(obj => obj.index);
You can omit the last map
if you want to keep both the indices and the values that go with them in your result.
Solution 3:
If you just sort it right away, you are definitely going to lose information about the indexes. What you can do is map the array with the values to an array with the index and the value (so that you don't lose information later), then you sort it, but you change the criteria of the sort method in order to get the indexes with top values.
const arr = [2, 1, 0, 3];
const getTopN = (arr, n = 10) => {
const _arr = arr.map((value, index) => [value, index]);
// by using b[0] - a[0] instead of a[0] - b[0] we can get the array in non-increasing order
_arr.sort((a, b) => b[0] - a[0])
return _arr.slice(0, n).map(([_, index]) => index);
}
console.log(getTopN(arr))
The getTopN
function does the job.