motipai
motipai

Reputation: 328

get the first and second highest values of an array using javascript

I am trying to perform the following code:

function oldestAges(ages){
    if (ages == []){
      return [0,0]; 
    }else{
      var max = Math.max.apply(null, ages); 
              ages.splice(ages.indexOf(max), 1); 
      var max2 = Math.max.apply(null, ages); 
      return [max2,max];
  }
}

However, when testing [] as ages, the expected was '[0, 0]', instead got: '[-Infinity, -Infinity]'

Also, is there a much easier way to accomplish the same task? I ask because using R I could get the same result in much less number of lines. I am noob in javascript still.

Upvotes: 2

Views: 3047

Answers (3)

Fatih Aktaş
Fatih Aktaş

Reputation: 1564

ages.length == 0 is what you can use to see if the number of the elements in the array is zero.

Your code has an error where you say if (ages == []).

Try this,

function oldestAges(ages){
        if (ages.length == 0){
          return [0,0];
        }else{
          var max = Math.max.apply(null, ages);
                  ages.splice(ages.indexOf(max), 1);
          var max2 = Math.max.apply(null, ages);
          return [max2,max];
      }
    }

Upvotes: 1

Jeto
Jeto

Reputation: 14927

A simple (not sure about the most optimal) way to achieve this:

const input = [5, 150, 2, 8, 58, 4];

const result = input.sort((x, y) => y - x).slice(0, 2);

console.log(result);

Upvotes: 4

user10243107
user10243107

Reputation:

You can sort your array in descending order so that the first two elements contain the highest values.

ages.sort((a, b) => b - a);

Now ages[0] and ages[1] contain the two biggest numbers.

Upvotes: 1

Related Questions