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.

gdh48k
  • 29
  • 6
  • Possible duplicate of [How to sort 2 dimensional array by column value?](https://stackoverflow.com/questions/16096872/how-to-sort-2-dimensional-array-by-column-value) – adiga May 06 '19 at 20:25

2 Answers2

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]

}
Mark
  • 90,562
  • 7
  • 108
  • 148
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];
}
mbhargav294
  • 389
  • 1
  • 3
  • 15