![](/img/trans.png)
[英]How to group an array of objects based on multiple keys in Javascript?
[英]How to group array based on multiple keys conditionally?
我有條件地將一個簡單的問題分組。
const aInput = [
{"date":"2018/9/10", "code":"A"},
{"date":"2018/9/10", "code":"B"},
{"date":"2018/9/11", "code":"B"},
{"date":"2018/9/11", "code":"B"}];
我想按日期和代碼對數組進行分組,但如果A和B都存在一天,那么只有B停留
const aInput = [ {"date":"2018/9/10", "code":"A"}, {"date":"2018/9/10", "code":"B"}, {"date":"2018/9/11", "code":"B"}, {"date":"2018/9/11", "code":"B"}]; // I want to group the array above by day & code BUT if there is both A & B then only B stays const aOutput = [ {"date":"2018/9/10", "code":"B"}, {"date":"2018/9/11", "code":"B"}]
您可以使用reduce
類似的操作:
創建一個以每個date
為鍵的累加器。 如果累加器的上下文中沒有當前日期,或者當前對象具有首選代碼,則將該對象添加為值。
(添加了一個額外的A
代碼對象來演示)
const aInput = [ {"date":"2018/9/10", "code":"A"}, {"date":"2018/9/10", "code":"B"}, {"date":"2018/9/11", "code":"B"}, {"date":"2018/9/11", "code":"B"}, {"date":"2018/9/12", "code":"A"}] const preferredCode = "B"; const merged = aInput.reduce((r,{date, code}) =>{ if(!r[date] || code === preferredCode) r[date] = {date, code}; return r; },{}) const final = Object.values(merged) console.log(final)
上面的代碼假定只有2個code
。 如果您有兩個以上的code
並且您希望每天獲取所有唯一代碼(除非有B
,那么可以使用reduce
和some
代碼來完成以下操作
const aInput = [ {"date":"2018/9/10", "code":"A"}, {"date":"2018/9/10", "code":"B"}, {"date":"2018/9/11", "code":"B"}, {"date":"2018/9/11", "code":"B"}, {"date":"2018/9/12", "code":"A"}, {"date":"2018/9/12", "code":"C"}] const preferredCode = "B"; const merged = aInput.reduce((r,{date, code}) =>{ r[date] = r[date] || []; if(code === preferredCode) r[date] = [{date, code}] else if(!r[date].some(e => e.code === preferredCode || e.code === code)) r[date].push({date, code}) return r; },{}) const final = [].concat.apply([],Object.values(merged)) console.log(final)
您可以使用.reduce
在此數組中按代碼分組
const aInput = [ {"date":"2018/9/10", "code":"A"}, {"date":"2018/9/10", "code":"B"}, {"date":"2018/9/11", "code":"B"}, {"date":"2018/9/11", "code":"B"}]; const result = aInput.reduce((r, a) => { r[a.code] = [...r[a.code] || [], a]; return r; }, {}); console.log(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.