Telmo Ivo
Telmo Ivo

Reputation: 4328

Undefined array after push

I'm trying to obtain to sort an array of mountain from the tallest to the smallest but when trying to print, I get

TypeError: mountainArray[i] is undefined

I think i'm not missing any step for the solution but I get undefined.

Thanks in advance

Code below:

var position;
var height;

function Mountain(position, height) {
  this.position = position;
  this.height = height;
}

function sortMountain(a, b) {
  return b.height - a.height;
}

var mountainArray = [];

// game loop
while (true) {
  for (var i = 0; i < 8; i++) {
    var mountainH = parseInt(readline()); // represents the height of one mountain, from 9 to 0.

    mountainArray.push(Mountain(i, mountainH));
    mountainArray.sort(sortMountain);


  }
  for (var i = 0; i < 8; i++) {
    print(mountainArray[i].position);
  }
}

Upvotes: 1

Views: 122

Answers (1)

omarjmh
omarjmh

Reputation: 13888

The way you have your class written:

function Mountain(position, height) {
  this.position = position;
  this.height = height;
}

You need to use the new keyword when you push:

while (true) {
  for (var i = 0; i < 8; i++) {
    var mountainH = parseInt(readline()); // represents the height of one mountain, from 9 to 0.

    mountainArray.push(new Mountain(i, mountainH)); // HERE
    mountainArray.sort(sortMountain);


  }
  for (var i = 0; i < 8; i++) {
    print(mountainArray[i].position);
  }
}

as pointed out in the comments, you should only sort once, no need to do it every time in your loop.

Upvotes: 2

Related Questions