我觉得可能有更好的解决方案,因为我在下面的例程(地图和排序)中重复代码。过滤器,地图,排序和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