我覺得可能有更好的解決方案,因爲我在下面的例程(地圖和排序)中重複代碼。過濾器,地圖,排序和concat
這是一個讀取(1或null)和未讀狀態(0)的消息的任意列表。我在頂部顯示未讀消息,在底部讀取消息,並應用一些排序和映射,然後在尾部連接兩個結果。
var unread = data.filter(function(item){
return item.Read == 0;
}).map(function(item){
return {Id: item.Id, First: item.First.toLowerCase(), Last: item.Last.toLowerCase()}
}).sort(function(a, b){
if (a.Last < b.Last) return -1;
if (a.Last > b.Last) return 1;
return 0;
});
var read = data.filter(function(item){
return item.Read == null || item.Read == 1;
}).map(function(item){ // lowercase (first, last) and sort the list by last
return {Id: item.Id, First: item.First.toLowerCase(), Last: item.Last.toLowerCase()}
}).sort(function(a, b){
if (a.Last < b.Last) return -1;
if (a.Last > b.Last) return 1;
return 0;
});
var finalData = unread.concat(read);
編輯
var input = [
{Id: 1, First: "John", Last: "B", Read:0},
{Id: 1, First: "Jane", Last: "C", Read:0},
{Id: 1, First: "Doe", Last: "D", Read:1},
{Id: 1, First: "Alpha", Last: "B", Read:1},
{Id: 1, First: "Beta", Last: "C", Read:null},
];
var output = [
{Id: 1, First: "Alpha", Last: "B", Read:1},
{Id: 1, First: "Doe", Last: "D", Read:1},
{Id: 1, First: "Beta", Last: "C", Read: null},
{Id: 1, First: "John", Last: "B", Read:0}
{Id: 1, First: "Jane", Last: "C", Read:0},
];
添加輸入和預期的輸出到你的問題。 –
編輯了一些數據 – Devyiweid