表格在两列上排序

时间:2013-03-08 12:40:13

标签: javascript sorting

我在找到表格排序问题的解决方案时遇到了一些麻烦。

我的表基本上是一个文件目录:

Name          FileSize    FileType
folder1/      -           folder
folder2/      -           folder
abc.pdf       3.2MB       pdf
def.jpg       1.2MB       jpg
ghi.doc       1.5MB       doc

我希望无论哪个列被排序,目录都会保留在表的顶部。例如,对“Name”进行排序将按名称对目录进行排序,然后按名称对文件进行排序。基本上,所有种类都需要首先对FileType进行排序,其中“folders”是最高值,然后是名称或文件大小。

我一直在使用臭名昭着的“频率解码器”排序脚本,但如果它更容易使用它会欢迎另一个脚本。

3 个答案:

答案 0 :(得分:0)

有一个jquery tablesorter插件适合你。

http://tablesorter.com/docs/

使用此插件,您可以禁用一些要缩短的内容

http://tablesorter.com/docs/example-meta-headers.html

答案 1 :(得分:0)

对于每个文件夹名称,将字符串String.fromCharCode(0)添加到前面,这些字符串将始终按字母顺序排在任何其他字符串之前,但将仅显示为名称。

例如

String.fromCharCode(0)+"folder1/";
String.fromCharCode(0)+"folder2/";

尽管如此,在任何比较中都是如此

String.fromCharCode(0)+“folder1 /”不等于“folder1 /”

答案 2 :(得分:0)

你怎么说? 排序脚本检查对象是否是文件夹,将其放在顶部,然后处理实际排序(包含文件夹和文件的文件夹)。

var files = [
  {
    name    : 'folder2/',
    filesize: null,
    filetype: 'folder'
  },
  {
    name    : 'folder1/',
    filesize: null,
    filetype: 'folder'
  },
  {
    name    : 'def.jpg',
    filesize: '1.2',
    filetype: 'jpg'
  },
  {
    name    : 'abc.pdf',
    filesize: '3.2',
    filetype: 'pdf'
  },
  {
    name    : 'ghi.doc',
    filesize: '1.5',
    filetype: 'doc'
  },
  {
    name    : 'jkl.doc',
    filesize: '1.1',
    filetype: 'doc'
  },
  {
    name    : 'pqr.pdf',
    filesize: '3.5',
    filetype: 'pdf'
  },
  {
    name    : 'mno.pdf',
    filesize: '3.5',
    filetype: 'pdf'
  }
];

/**
 * Sort an array of files and always put the folders at the top.
 * @access public
 * @param  {Array} array to sort
 * @param  {String} column to sort
 * @param  {Bool} asc
 * @return void
 */
function sortBy(array, column, asc) {
  if (asc == null) {
    asc = true;
  }

  array.sort(function(a, b) {

    // Put at the top the folders.
    if (a.filetype == 'folder' && b.filetype != 'folder') {
      return false;

    // Sort between folders.
    // The folders don't have a filesize and the type is always the same.
    // Process as a sort by name.
    // It doesn't need to respect the sens of sorting.
    } else if ((column == 'filesize' || column == 'filetype') && a.filetype == 'folder' && b.filetype == 'folder') {
      return a.name > b.name;

    // Normal sort.
    // The folders will be sorted together and the files togethers.
    } else {
      return asc ? a[column] > b[column] : a[column] < b[column];
    }

  });
}

sortBy(files, 'name', false);
console.log('by name', files);

sortBy(files, 'filesize', true);
console.log('by size', files);

sortBy(files, 'filetype', false);
console.log('by type', files);