Romano
Romano

Reputation: 117

Get the highest but also unique number from an array

I have a question. I'm looking for a way to get the higest unique number of an array.

var temp = [1, 8, 8, 8, 4, 2, 7, 7];

Now I want to get the output 4 since that is the unique highest number.

Is there a good & hopefully short way to do that?

Upvotes: 0

Views: 103

Answers (3)

Louis
Louis

Reputation: 583

Using the spread operator you can find the hightest number easily

Math.max(...numArray);

The only thing left then is to either filter duplicates from the array beforehand, or remove all the elements that match your maximum number if its a duplicate.

remove beforeHand would be easiest in es6 like this.

Math.max(...numArray.filter(function(value){ return numArray.indexOf(value) === numArray.lastIndexOf(numArray);}));

For a non es6 compatible way to remove duplicates have a look at Remove Duplicates from JavaScript Array, the second answer contains an extensive examinations of several alternatives

Upvotes: 0

NickT
NickT

Reputation: 214

If you don't want to get fancy, you can use a sort and loop to check the minimal number of items:

var max = 0;
var reject = 0;

// sort the array in ascending order
temp.sort(function(a,b){return a-b});
for (var i = temp.length - 1; i > 0; i--) {
  // find the largest one without a duplicate by iterating backwards
  if (temp[i-1] == temp[i] || temp[i] == reject){
     reject = temp[i];
     console.log(reject+" ");
  }
  else {
     max = temp[i];
     break;
  }

}

Upvotes: 1

Bergi
Bergi

Reputation: 664385

Yes, there is:

Math.max(...temp.filter(el => temp.indexOf(el) == temp.lastIndexOf(el)))

Explanation:

  1. First, get the elements which are unique in the array using Array#filter

    temp.filter(el => temp.indexOf(el) === temp.lastIndexOf(el)) // [1, 4, 2]
    
  2. Now, get the max of the numbers from the array using ES6 spread operator

    Math.max(...array) // 4
    

    This code is equivalent to

    Math.max.apply(Math, array);
    

Upvotes: 2

Related Questions