按数字项对2D数组排序 [英] Sorting 2D Array by numeric item

查看:70
本文介绍了按数字项对2D数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用第5列(Pts)对这个数组进行排序.

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]];

这是一个包含Pld,W,D,L和Pts列的足球联赛表.我打算稍后添加目标差异.

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

我尝试了以下代码:

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

不幸的是,代码甚至没有运行.我得到了错误 cannot read property '5' of undefined.

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

推荐答案

您无需索引到表中.迭代通过将每一行传递到函数中(而不是行索引)来实现,只需索引所需的列即可.您可以使用-而不是if来获得相同的效果:

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]

}

这篇关于按数字项对2D数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆