javascript按字符串属性排序对象数组

时间:2017-08-28 17:56:03

标签: javascript

我正在尝试按属性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>

5 个答案:

答案 0 :(得分:6)

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

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);

答案 1 :(得分:2)

使用&lt;或者&gt;比较比较函数中的字符串时的运算符。

see documentation

答案 2 :(得分:1)

减法用于数值运算。请改用a.title.localeCompare(b.title)

&#13;
&#13;
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();
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您可以从https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

尝试此代码
<a onClick="window.location.reload()">Refresh</a>

答案 4 :(得分:-1)

你能试试吗

FOR DESC

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

或 FOR ASC

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