Javascript - Sắp xếp mảng đối tượng theo tiêu đề
Sắp xếp mảng đối tượng theo tiêu đề
Ví dụ:
Mã nguồn:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Write a JavaScript function to sort an lowing array of objects by title value.</title>
<script>
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}
];
function compare_to_sort(x,y)
{
if (x.title < y.title)
return -1;
if (x.title > y.title)
return 1;
return 0;
}
document.write(library.sort(compare_to_sort));
</script>
</head>
<body>
Lưu đồ thuật toán: