1

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);
  }
}

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

the readline is called before. the issue was missing the new part from mountainArray.push(new Mountain(i, mountainH)); seems I need to learn JS from the scratch
Also should only sort array once...not each iteration of loop
Note that while the code correctly fixes the error, the text is a little off. new has nothing to do with pushing. You need new because you have a plain constructor function in Mountain, which doesn't return anything if you don't use it with new. You could use push without new if you chose to write Mountain in a different manner.
^^^ I put that in there, right before your comment. thanks
Sure enough. It might be good to note that there are those who find new (and this) horrible features of JS. I'm not one of them, but I do sympathise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.