0

I asked the same kind of question here How to sort an ArrayList using a Map key as list object and value as the order?

But I need an equivalent for JavaScript. I need to keep the order of my list of objects as it can be changed and reordered anytime in my webapp.

In my model I have a array list of objects example

objectList = [object1, object2, object3, object4]

and I save the order of each object belonging to this instance to a another object example:

order

{
   "object1":4,
   "object2":2,
   "object3":1,
   "object4":3
}

Therefore i want to sort my list according to its value in the order object's property retrieved by the objects Id as the key:

Expected result:

[object3, object2, object4, object1]

In Java this works

objectList.sort(Comparator.comparing(o -> yourMap.get(o.getId()));

However I am unsure how to achieve this same sort in JavaScript

EDIT Just to clarify, I do not want to sort the order object. I want to sort my objectList using its order maintained in the order object

Dean Strydom
  • 275
  • 5
  • 17

2 Answers2

0

The order of object keys are never guaranteed. You can create an array of the object values, using Object.values and then sort them

const data = {
  "object1": 4,
  "object2": 2,
  "object3": 1,
  "object4": 3
};
const sortedVal = Object.values(data).sort((a, b) => a - b);
console.log(sortedVal)
brk
  • 48,835
  • 10
  • 56
  • 78
0

This does the trick and retrieves order value by using the objects id for the key. Then we just compare these values for sorting

this.objectList.sort(function(a, b)
    {
      if(order[a._id] > order[b._id]) return 1;
      if(order[b._id] > order[a._id]) return -1;

      return 0;
    });
Dean Strydom
  • 275
  • 5
  • 17