Javascript - Sắp xếp một mảng các đối tượng
Viết chương trình JavaScript để sắp xếp một mảng các đối tượng
Ví dụ:
Nhập
Sample Object:
var library = [
{
title: 'The Road Ahead',
author: 'Bill Gates',
libraryID: 1254
},
{
title: 'Walter Isaacson',
author: 'Steve Jobs',
libraryID: 4264
},
{
title: 'Mockingjay: The Final Book of The Hunger Games',
author: 'Suzanne Collins',
libraryID: 3245
}];
Xuất kết quả:
[[object Object] {
author: "Walter Isaacson",
libraryID: 4264,
title: "Steve Jobs"
}, [object Object] {
author: "Suzanne Collins",
libraryID: 3245,
title: "Mockingjay: The Final Book of The Hunger Games"
}, [object Object] {
author: "The Road Ahead",
libraryID: 1254,
title: "Bill Gates"
}]
Sample Solution: -
Mã nguồn:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript program to sort an array of JS objects</title>
<script>
var library = [
{
title: 'Bill Gates',
author: 'The Road Ahead',
libraryID: 1254
},
{
title: 'Steve Jobs',
author: 'Walter Isaacson',
libraryID: 4264
},
{
title: 'Mockingjay: The Final Book of The Hunger Games',
author: 'Suzanne Collins',
libraryID: 3245
}];
var sort_by = function(field_name, reverse, initial){
var key = initial ?
function(x)
{
return initial(x[field_name]);
} :
function(x)
{
return x[field_name];
};
reverse = !reverse ? 1 : -1;
return function (x, y) {
return x = key(x), y = key(y), reverse * ((x > y) - (y > x));
} ;
};
var newobj = library.sort(sort_by('libraryID', true, parseInt));
document.write(newobj);
</script>
</head>
<body>
</body>
</html>
Lưu đồ thuật toán: