0

I'd like to sort this array using column 5 (Pts).

var table=[
  ["teamA",6,2,0,2,6],
  ["teamB",6,1,1,2,4],
  ["teamC",6,2,1,1,7]];

It's a football league table with Pld, W, D ,L and Pts columns. I plan to add goal difference later.

I've attempted the code below:

console.log(table.sort(compare));

function compare( a, b ) {
  if (table[a][5]<table[b][5]){
    return -1;
  }
  if (table[a][5]>table[b][5]){
    return 1;
  }
  return 0;
}

Unfortunately the code doesn't even run. I get the error cannot read property '5' of undefined.

1

2 Answers 2

1

You don't need to index into the table. The iteration does that by passing each row into the function (not the row index), just index the column you want. You can use - instead of the if to get the same effect:

var table = [
  ["teamA", 6, 2, 0, 2, 6],
  ["teamB", 6, 1, 1, 2, 4],
  ["teamC", 6, 2, 1, 1, 7]
];

console.log(table.sort(compare));

function compare(a, b) {
  return a[5] - b[5]

}

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

Comments

0

Your compare method will receive actual objects within the array and not the index of these objects. So, refactor your compare method to this:

function compare( a, b ) {
  if (a[5] < b[5]){
    return -1;
  }
  if (a[5]>n[5]){
    return 1;
  }
  return 0;
}

This can be further simplified to this:

function compare( a, b ) {
  return a[5] - b[5];
}

Comments

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.