JS sort object by "x" in array
This question already has an answer here:
你可以使用Array.sort()
array.sort(function(a, b) {
return a.album < b.album;
});
var array = [
{'key' : '1', 'title' : 'title', 'source' : 'path/to/image', 'album' : 'album1'},
{'key' : '1', 'title' : 'title', 'source' : 'path/to/image', 'album' : 'album2'},
{'key' : '1', 'title' : 'title', 'source' : 'path/to/image', 'album' : 'album3'},
{'key' : '1', 'title' : 'title', 'source' : 'path/to/image', 'album' : 'album6'},
{'key' : '1', 'title' : 'title', 'source' : 'path/to/image', 'album' : 'album5'},
{'key' : '1', 'title' : 'title', 'source' : 'path/to/image', 'album' : 'album7'},
{'key' : '1', 'title' : 'title', 'source' : 'path/to/image', 'album' : 'album6'}
];
array.sort(function(a,b){ return a.album > b.album;} );
console.log(array);
http://jsbin.com/xefujehe/1/
Check out the docs on MDN for Array.prototype.sort.
This method takes a comparison function. Here's an example:
function compare(a, b) {
if (a is less than b by some ordering criterion)
return -1;
if (a is greater than b by the ordering criterion)
return 1;
// a must be equal to b
return 0;
}
Here's how you'd sort on the album name:
var albums = [
{
key: 110000,
album: 'Starry nights'
}, {
key: 100,
album: 'Zebra kills Zebra'
}, {
key: 1,
album: 'Alfred Hitcock Presents'
}, {
key: 50,
album: 'baby whales'
}];
albums.sort(function(a, b){
return a.album === b.album ? 0 : a.album > b.album;
});
console.log(albums);
jsfiddle.
Be aware while sorting that all capital letters come before all lowercase letters
链接地址: http://www.djcxy.com/p/19334.html上一篇: 根据对象中的值对一组对象进行排序
下一篇: JS按数组中的“x”排序对象