2017-08-28 195 views
0

我想通过属性title对对象数组排序。这是我正在运行的代码片段,但它不排序任何东西。该数组按原样显示。我看过以前的类似问题。这个例如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> 
+0

“比尔盖茨” - “史蒂夫乔布斯”应该是什么?无限或更不是数字;)? –

回答

1

你试过这样吗?它工作正常

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

编号:Sort array of objects by string property value in JavaScript

0

减法是数字运算。改为使用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();

1

使用<或>比较在您的比较功能字符串时操作。

see documentation

+1

对此实例使用>操作符时,在使用>替换minus操作符时可以使用。 –

+1

@ jonathan.ihm:'.sort()'回调需要一个数字结果,而不是布尔值,因此不仅仅需要一个插入替换。 – spanky

+0

我在控制台中运行它并确认它立即工作。另请参阅https://stackoverflow.com/questions/51165/how-to-sort-strings-in-javascript –

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