2017-04-27 6 views
0

私は2つのリストを持っています。私は既存のIDが更新され、新しいIDがリストに追加された後にIDでソートされるように、それらを新しいリストに結合しようとしています。これを行うより効率的な方法がありますか?2つの不変リストを組み合わせる最良の方法は何ですか?

// Original list 
const list = Immutable.List([ 
    { id: 1, name: 'List Item 1' }, 
    { id: 2, name: 'List Item 2' }, 
    { id: 3, name: 'List Item 3' }, 
]); 

// One updated item and two new items 
const newList = Immutable.List([ 
    { id: 2, name: 'Updated List Item 2' }, 
    { id: 4, name: 'New List Item 4' }, 
    { id: 5, name: 'New List Item 5' }, 
]); 

// Get updated ids 
const ids = newList.map((item) => item.id); 

// Filter out updated ids from orignial list 
const filteredList = list.filterNot(item => ids.includes(item.id)); 

// Concat and sort by id 
const concatList = newList 
    .concat(filteredList) 
    .sortBy(item => item.id); 

console.log(concatList.toJS()); 

/* Outputs as desired 
[ 
    { id: 1, name: "List Item 1" }, 
    { id: 2, name: "Updated List Item 2" }, 
    { id: 3, name: "List Item 3" }, 
    { id: 4, name: "New List Item 4" }, 
    { id: 5, name: "New List Item 5" } 
] 
*/ 

答えて

2

これはreducemergeを使用して、私はそれを行うだろうかです:

function reduceToMap(result, item) { return result.set(item.id, item) } 
 

 
const list = Immutable.List([ 
 
    { id: 1, name: 'List Item 1' }, 
 
    { id: 2, name: 'List Item 2' }, 
 
    { id: 3, name: 'List Item 3' }, 
 
]).reduce(reduceToMap, Immutable.Map()); 
 

 
// One updated item and two new items 
 
const newList = Immutable.List([ 
 
    { id: 2, name: 'Updated List Item 2' }, 
 
    { id: 4, name: 'New List Item 4' }, 
 
    { id: 5, name: 'New List Item 5' }, 
 
]).reduce(reduceToMap, Immutable.Map()); 
 

 

 
console.log(...list.merge(newList).values())
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.js"></script>

関連する問題