0

我可以用这个答案按列对数组进行排序它看起来有点像这样:

var myArr = [ [0, 10, 20, "果酱"], [1, 20, 14, "胡萝卜"], [2, 30, 14, "奶油冻"], [3, 40, 16, "牛肉" ], [4, 0, 16, "格温"], ]

myArr.sort(sort_2d_array);

function sort_2d_array(arr) 
{

  var column = 1;

  if (a[column] === b[column]) 
  {
    return 0;
  }
  else
  {
    return (a[column] < b[column]) ? -1 : 1;
  }
}

排序为: 4, 0 , 16, "gwen" 0, 10, 20, "jam" 1, 20, 14, "carrots" 2, 30, 14, "custard" 3, 40, 16, "beef"

但是,由于它是作为函数表达式编写的,如果我想将列作为参数传递给函数,该如何编写呢?没有具有不同值 vorm 的相同函数的 4 个版本column

就个人而言,我发现以传统形式更容易理解和理解:

function sort_2d_array_by_column(arr, column) 

还是本末倒置?

如果这没有意义,我会再写一次。#spectrumofconfusion

4

2 回答 2

1

您可以对索引进行闭包并将排序函数作为回调返回。

var sortByIndex = function (index) {
        return function (a, b) {
            return (a[index] > b[index]) - (a[index] < b[index]);
        };
    },
    array = [[0, 10, 20, "jam"], [1, 20, 14, "carrots"], [2, 30, 14, "custard"], [3, 40, 16, "beef"], [4, 0, 16, "gwen"]];

array.sort(sortByIndex(1));
console.log(array);

array.sort(sortByIndex(3));
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

于 2021-05-17T10:49:37.670 回答
1

让我们在这里进行一些函数式编程:

const cmp = (a, b) => (a > b) - (a < b)
const column = p => o => o[p]
const by = f => (x, y) => cmp(f(x), f(y))


myArr = [
    [0, 10, 20, "jam"],
    [1, 20, 14, "carrots"],
    [2, 30, 14, "custard"],
    [3, 40, 16, "beef"],
    [4, 0, 16, "gwen"],
]

myArr.sort(by(column(2)));
console.log(myArr.map(JSON.stringify))


myArr.sort(by(column(3)));
console.log(myArr.map(JSON.stringify))

一个不太“高级”,但可能更具可读性(和 ES3 兼容)的版本:

function sortByColumn(arr, col) {
    return arr.sort(function(x, y) {
        x = x[col]
        y = y[col]
        return (x > y) ? 1 : (x < y ? -1 : 0)
    })
}
于 2021-05-17T10:54:06.487 回答