Search code examples
javascriptimmutable.js

Keep order of Immutable JS Map


I have a JavaScript Array looking like this

const data = 
[
   {
       id: 19,
       date: 01.01.2001,
       content: ...
   },
   {
       id: 85,
       date: 10.10.2002,
       content: ...
   },
   {
       id: 1113,
       date: 07.09.2018,
       content: ...
   },
   ...
];

Originally, data is unsorted when it comes from the server. I sort data by date, keeping it in an array to preserve its order.

const data = 
[
   {
       id: 1113,
       date: 07.09.2018,
       content: ...
   },
   {
       id: 85,
       date: 10.10.2002,
       content: ...
   },
   {
       id: 19,
       date: 01.01.2001,
       content: ...
   },
   ...
];

However, accessing an element with an id, will result in iteration over the whole array. Storing them in an object with this structure

const obj = 
{
    19: {
            date: 01.01.2001,
            content: ...,
         },
    85: {
            date: 10.10.2002,
            content: ....,
        },
    1113: {
            date; 07.09.2018,
            content: ...
          }
}

will make the access easier, but it will not be sorted. I am looking for a Immutable JS way to store the data in an Map, like obj, but keeping its order but date. The key is supposed to be the id.

How do I sort by date, but keep id as key?


Solution

  • I suppose that you've already solved this by now. But Immutable.orderedMap seems to be a perfect solution fo you.

    https://immutable-js.github.io/immutable-js/docs/#/OrderedMap