通过字符串属性排序对象的数组

这个问题在这里已经有了答案:

  • 通过JavaScript中的字符串属性值排序对象数组33个答案

  • 你有这样的尝试吗? 它按预期工作

    library.sort(function(a,b) {return (a.title > b.title) ? 1 : ((b.title > a.title) ? -1 : 0);} );
    

    var library = [
        {
            author: 'Bill Gates',
            title: 'The Road Ahead',
            libraryID: 1254
        },
        {
            author: 'Steve Jobs',
            title: 'Walter Isaacson',
            libraryID: 4264
        },
        {
            author: 'Suzanne Collins',
            title: 'Mockingjay: The Final Book of The Hunger Games',
            libraryID: 3245
        }
    ];
    console.log('before sorting...');
    console.log(library);
    library.sort(function(a,b) {return (a.title > b.title) ? 1 : ((b.title > a.title) ? -1 : 0);} );
    
    console.log('after sorting...');
    console.log(library);

    比较函数中的字符串时使用<或>运算符。

    见文档


    减法用于数字操作。 改为使用a.title.localeCompare(b.title)

    function sortLibrary() {
      console.log("inside sort");
      library.sort(function(a, b) {
        return a.title.localeCompare(b.title);
      });
      console.log(library);
    }
    
    var library = [{
        author: 'Bill Gates',
        title: 'The Road Ahead',
        libraryID: 1254
      },
      {
        author: 'Steve Jobs',
        title: 'Walter Isaacson',
        libraryID: 4264
      },
      {
        author: 'Suzanne Collins',
        title: 'Mockingjay: The Final Book of The Hunger Games',
        libraryID: 3245
      }
    ];
    
    sortLibrary();
    链接地址: http://www.djcxy.com/p/19331.html

    上一篇: javascript sorting array of objects by string property

    下一篇: javascript sort and sort equals on result. how?