2017-08-28 190 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;}); 
相關問題