javascript sorting array of objects by string property
This question already has an answer here:
Have you tried like this? It is working as expected
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);
Use the < or > operator when comparing strings in your compare function.
see documentation
Subtraction is for numeric operations. Use a.title.localeCompare(b.title)
instead.
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();
链接地址: http://www.djcxy.com/p/19332.html
上一篇: JS按数组中的“x”排序对象
下一篇: 通过字符串属性排序对象的数组