0

假设我有以下数据集

Company    S1   S2   S3
Apple.com  0.40 0.28 1.00
Google.com 0.30 0.58 0.99

假设上面的内容在 HTML 表格中。

我已经设法弄清楚如何分别对 S1、S2 和 S3 进行排序。但是,我很想知道如何将它们分组。

  • 如果我对 S1 进行从高到低的排序。苹果应该是最重要的
  • 如果我将 S2 从最高到最低排序。谷歌应该是最重要的。
  • 如果我根据 S1 和 S2 进行排序,Google 应该排在首位,因为它们的平均值更高。
  • 最后,如果我根据 S1 和 S3 排序,Apple 应该更高......原始数据是从数据库中提取并使用 PHP 填充的。我知道我可以在 PHP 中执行此逻辑,但是,我希望用户能够即时重新排序列表*。

任何 jQuery/Javascript 方法可以做到这一点? 编辑:

注意这一点

作者在按下时对每一列进行排序。但是,我希望能够“检查”两列并按它们的平均值排序。

编辑2:

我想选择 n 列进行平均。其中 n 是 [1..infinity] 的一个元素。

只想高高在上。也就是说,不需要反向排序。

4

1 回答 1

0

我认为这样的事情会做到这一点,基于对普通对象的排序,如果你可以将它转回你的表格:

var sortCompanies = function(cols, companies) {
    if (!cols || !cols.length) {
        companies.sort(function(a, b) {return a.name < b.name ? -1 : a.name > b.name ? 1 : 0});
        return companies;
    }
    companies.forEach(function(company) {
        company.sortKey = 0;
        cols.forEach(function(col) {
            company.sortKey += (company[col] || 0);
        });
    });
    companies.sort(function(a, b) {return b.sortKey - a.sortKey;});
    return companies;
};

var companies = [
    {name: 'Apple.com', S1: 0.40, S2: 0.28, S3: 1.00},
    {name: 'Google.com', S1: 0.30, S2: 0.58, S3: 0.99}
];

sortCompanies(['S1'], companies);             //=> Apple, Google
sortCompanies(['S1', 'S2'], companies);       //=> Google, Apple
sortCompanies(['S3'], companies);             //=> Apple, Google
sortCompanies(['S1', 'S2', 'S3'], companies); //=> Google, Apple
于 2013-07-09T20:14:55.023 回答