JavaScript按字符串属性对对象数组进行排序

13

我正在尝试通过属性title对对象数组进行排序。 这是我运行的代码片段,但它不会对任何内容进行排序。 数组按原样显示。 P.S 我查看了以前类似的问题。 例如,这个here建议使用我正在使用的相同方法。

Javascript代码:

function sortLibrary() {
    // var library is defined, use it in your code
    // use console.log(library) to output the sorted library data
    console.log("inside sort");
    library.sort(function(a,b){return a.title - b.title;});
    console.log(library);
} 

// tail starts here
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();

HTML代码:

<html>
<head>
    <meta charset="UTF-8">
</head>

<body>
<h1> Test Page </h1>
<script src="myscript.js"> </script>
</body>

</html>

"比尔·盖茨" - "史蒂夫·乔布斯" 应该是什么?无穷大还是非数字(NaN)? - Jonas Wilms
5个回答

16
你尝试过这样吗?它按预期工作。
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);


有没有办法按照另一个预设的数组来排序,而不是按字母顺序呢?例如,在一个函数名称列表中按照一组预设的函数顺序进行排序(如厨师在副厨师之上,在厨师助手之上,...)。 - nclsvh

4

减法适用于数值运算。使用 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();


2

在您的比较函数中,当比较字符串时,请使用 < 或者 > 运算符。

查看文档


1
在这种情况下使用 > 运算符,当用 > 替换减号运算符时,它会起作用。 - jonathan.ihm
1
@jonathan.ihm:.sort() 回调函数期望一个数字结果,而不是布尔值,因此需要更多的替换才能实现。 - spanky
我在控制台中运行它并立即确认它可以正常工作。另请参阅https://dev59.com/AnVD5IYBdhLWcg3wNY1Z - jonathan.ihm
我改口了。请参考https://dev59.com/1pLea4cB1Zd3GeqP12vv。 - jonathan.ihm

0

-1
请尝试这个:
按 DESC 排序
library.sort(function(a,b){return a.title < b.title;});

或者 按升序排序

library.sort(function(a,b){return a.title > b.title;});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接