2017-03-06 57 views
3

在ramda.js哪能組和字段排序列表,然後移動每個組的所有,但第一項到該項目的孩子嗎?Ramda組再轉換兄弟姐妹的孩子

如下面這裏,我的名字分組,並按日期排序下降:

[{ id: 1, name: 'bob', date: '2007-03-05', count: 15}, 
{ id: 2, name: 'bob', date: '2007-03-04', count: 32}, 
{ id: 3, name: 'bob', date: '2007-03-01', count: 27}, 
{ id: 4, name: 'jack', date: '2007-03-04', count: 3}, 
{ id: 5, name: 'jack', date: '2007-02-22', count: 5}] 

進入

[{ id: 1, name: 'bob', date: '2007-03-05', count: 15, 
    children: [{ id: 2, name: 'bob', date: '2007-03-04', count: 32}, 
    { id: 3, name: 'bob', date: '2007-03-01', count: 27}] 
}, 
{ id: 4, name: 'jack', date: '2007-03-04', count: 3, 
    children: [{ id: 5, name: 'jack', date: '2007-02-22', count: 5}] 
} 
] 

我知道,我可以抓住與R.head整個列表的頂部項目其餘的與R.tail一起,然後把它作爲一個孩子與R.merge一起添加,但我不知道如何在列表中抓住一個組的頂部或尾部。

回答

5

另一種方法:

const fn = pipe(
    groupBy(prop('name')), 
    values, 
    map(lift(assoc('children'))(tail, head)) 
); 

如果你想在這個排序,你可以values,後補充一點:

map(sort(descend(prop('date')))), 

如果這是晦澀:map(lift(assoc('children'))(tail, head))你可以用更換相當於:

map((group) => assoc('children', tail(group), head(group))) 

你可以看到這在行動Ramda REPL

+0

這太神奇了 –

3

您還沒有歸他們,只是名字命令他們。將它們組成陣列的陣列,使用R.groupWith

R.groupWith(R.eqProps("name")) 

將其應用於數據後,使用map創建從每個組中的對象。

2

這裏你可以得到想要的結果

const groupByName = groupBy(obj => obj.name); 
const sortByDate = sortBy(obj => obj.date); 
const grouped = pipe(groupByName, map(sortByDate), values); 

reduce((acc, val) => { 
acc.push(merge(head(val), {children: tail(val)})); 
return acc; 
}, [], grouped(data)); 
單程

Ramda snippet

2

可能有更好的方法來做到這一點,但我認爲這是一個開始:

function yourAnswer (data) { 
    const groupByName = groupBy((person) => person.name) 
    return (
    Object.values(groupByName(data)) 
    .map((g) => g.sort((a, b) => a.id - b.id)) // sort by ascending id 
    .map(function(g) { // for each group, sorted by id 
     const o = Object.assign(g[0]) // create an object from the minimal id 
     o['children'] = g.slice(1) // assign 'children' to be equal the other objects in the group 
     return o 
    }) 
)} 

let data = [{ id: 1, name: 'bob', date: '2007-03-05', count: 15}, 
      { id: 2, name: 'bob', date: '2007-03-04', count: 32}, 
      { id: 3, name: 'bob', date: '2007-03-01', count: 27}, 
      { id: 4, name: 'jack', date: '2007-03-04', count: 3}, 
      { id: 5, name: 'jack', date: '2007-02-22', count: 5}] 

console.log(yourAnswer(data)) 

在試用ramda repl