wasanga7
wasanga7

Reputation: 242

How can i get index of the five highest numbers in an array

I need a method that returns an array with five positions. The numbers of this arrays mean, in order, the index of the highest number in the array that come in the argument. I have this but i think there´s a better way to do it.

function calculateHighests(array){ // in array[array.lentgth-1] is saved a very low number
		var max1=max2=max3=max4=max5=array.length-1;
		for(var i=0;i<array.length;i++){
			if(array[i]>array[max5]){
				if(array[i]>array[max4]){
					if(array[i]>array[max3]){
						if(array[i]>array[max2]){
							if(array[i]>array[max1]){
								max1=i;
							} else {
								max2=i;
							}
						} else {
							max3=i;
						}
					} else {
						max4=i;
					}
				} else {
					max5=i;
				}
			}
		}
		res = [max1,max2,max3,max4,max5];
    return res;
 }
 
 var inp = [2, 4, 6, 5, 1, 3, 7, 8, 0];
 
 var out = calculateHighests(inp);
 
 console.log(out);

The numbers in the array can be repeated.

Upvotes: 0

Views: 91

Answers (4)

Maheer Ali
Maheer Ali

Reputation: 36594

You could first Array.prototype.sort() the array and then use Array.prototype.map() get array of indexes

function findMaxPositions(arr,n){
  return arr.slice(0).sort((a,b) => b-a).slice(0,n).map(x => arr.indexOf(x));
}

console.log(findMaxPositions([0,3,7,1,8,3,5,0,2,9],5));

If the numbers can repeat so follow the steps:

  • Use map() to create array of objects with index and value
  • Then use sort() sort the array on the base of value
  • Then use slice() to get the first 5 elements
  • Use map() again to convert the array of objects to array of indexes

function findMaxPositions(arr,n){
      return arr.map((val,ind) => ({val,ind})).sort((a,b) => b.val-a.val).slice(0,n).map(x => x.ind);
    }
    
    console.log(findMaxPositions([1,1,1,1,1],5))

Upvotes: 3

Slai
Slai

Reputation: 22876

Another option can be to sort the indexes :

var arr = [0,3,7,1,8,3,5,0,2,9];

var result = Object.keys(arr).sort(function(a, b) { return arr[b] - arr[a]; })
                   .slice(0, 5).map(Number);

console.log( JSON.stringify(result) );

Upvotes: 0

adiga
adiga

Reputation: 35253

You can sort the index-value pair array returned by Object.entries() and then use slice to get the top 5 indexes

let array = [10, 5, 7, 0, 4, 3, 8]

let output = Object.entries(array)
                    .sort((a, b) => b[1] - a[1])
                    .slice(0, 5)
                    .map(a => +a[0])
                    
console.log(output)

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138457

You could sort the array and keep the indices:

const calculateHighest = arr => arr
  .map((v, i) => ({ v, i }))
  .sort((a, b) => a.v - b.v)
  .slice(0, 5)
  .map(({ i }) => i);

Upvotes: 1

Related Questions