2015-01-14 253 views
0

我試圖選擇收件箱的最後一條消息,並將它們按topic_id分組在列表中。我想顯示每個主題的最後一條消息。Json和解決方案組

數組是這樣的:

[{ 
"id":"5", 
"topic_id":"4", 
"message_from":"24", 
"message":"how do you do?", 
"date":"2015-01-13 15:34:59" 
}, 
{ 
"id":"6", 
"topic_id":"1", 
"message_from":"33", 
"message":"go go go!!", 
"date":"2015-01-13 13:35:06" 
}, 
{ 
"id":"7", 
"topic_id":"4", 
"message_from":"33", 
"message":"Je suis charlie", 
"date":"2015-01-14 16:24:46" 
},.... 

是有一個解決方案做到這一點沒有一個循環?

+0

有你試圖在一個數據庫級別? –

+0

不,因爲我想要一個查詢並使用結果來列出最後的消息,並且還顯示主題提要,而不需要其他請求。 – Malakiof

+0

爲什麼你不喜歡帶循環的解決方案? –

回答

1

你不能沒有循環做到這一點,但你可以通過將事件順序分解成更小的函數來簡化它。你可能不喜歡這種方法,但它是最乾淨的imo。或者,您可以使用第三方庫(可能是下劃線?),允許您對數據運行分組。

基本上,獲取所有記錄的所有topic_id的列表,循環訪問該topic_id數組,併爲每個記錄提取最後一條記錄並將其添加到輸出數組。

// Get a list of all the topic ids - no duplicates 
function getTopicIds(arr) { 
    var out = []; 
    arr.forEach(function (el) { 
    if (out.indexOf(el.topic_id) === -1) out.push(el.topic_id); 
    }); 
    return out; 
} 

// Given a topic_id, filter the array for only those records 
// sort in desc order by id, and return the first record. 
// Given that each record has a unique id, and we know that older 
// messages will have higher ids, it's easier to sort by id than 
// date here 
function getLastMsg(id, arr) { 
    return arr.filter(function (el) { 
    return el.topic_id === id; 
    }).sort(function (a, b) { return +b.id - +a.id; })[0]; 
} 

// return a array of the last messages for each topic_id 
// in the records array 
function getLastMsgs(arr) { 
    return getTopicIds(arr).map(function (id) { 
    return getLastMsg(id, arr); 
    }); 
} 

var result = getLastMsgs(arr); 

DEMO