Re-order an immutable.js List from an array of indices

741 Views Asked by At

I have an Immutable list that populates a drag and drop list feature (there are no id's on the list item aside from their indices when mapping through them).

const list = Immutable.List([{"alias":"cat"},{"alias":"dog"},{"alias":"rat"}])

On dragEnd, the event gives me an array of the new order of the list, but does not give me anything to really identify the list items, aside from referencing the indices of the previous order.

const newOrder = [{"order":1},{"order":0},{"order":2}]

I need to dispatch a new re-ordered Immutable data list based on these indices to update my store, but have yet to find an eloquent and succinct way to do this. I was thinking perhaps some use of sortBy or maybe creating an orderedMap from the first list and referencing it from the newOrder array to create the orderedList?? Haven't been able to get anything to work that seems like a good solution.

Need to dispatch:

const orderedList = Immutable.List([{"alias":"dog"},{"alias":"cat"},{"alias":"rat"}])

What would be the best way to do this?

1

There are 1 best solutions below

1
On

I think you can use map:

const newOrder = [{"order":1},{"order":0},{"order":2}];

const ordered = 
Immutable.List([1,2,3])
  .map(
    (item,index,all)=>
      all.get(newOrder[index].order)
    );

console.log(
  JSON.stringify(
    ordered.toArray(),
    undefined,
    2
  )
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.min.js"></script>