tonilaukka
tonilaukka

Reputation: 65

What is the best way to combine two immutable lists?

I have two lists and i'm trying to combine them to a new list so that the existing ids are updated and the new ones are added to list and after that sorted by the id. Is there a better or more efficient way to do this?

// 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" }
]
*/

Upvotes: 0

Views: 2058

Answers (1)

thedude
thedude

Reputation: 9812

This is how I would do it, using reduce and merge:

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>

Upvotes: 2

Related Questions