javascript sorting array of objects by string property
本问题已经有最佳答案,请猛点这里访问。
我正在尝试按属性
JavaScript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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代码:
1 2 3 4 5 6 7 8 9 10 11 | <html> <head> <meta charset="UTF-8"> </head> <body> Test Page <script src="myscript.js"> </body> </html> |
你试过这样吗?它按预期工作
1 | library.sort(function(a,b) {return (a.title > b.title) ? 1 : ((b.title > a.title) ? -1 : 0);} ); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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(); |
您可以从https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/array/sort尝试此代码
1 2 3 4 5 6 7 8 9 10 11 | library.sort(function(a, b){ var tA = a.title.toUpperCase(); var tB = b.title.toUpperCase(); if (tA < tB) { return -1; } if (tA > tB) { return 1; } return 0; }) |
你能试试这个吗
为DESC
1 | library.sort(function(a,b){return a.title < b.title;}); |
或ASC
1 | library.sort(function(a,b){return a.title > b.title;}); |