1
const options = [ { "value": 11, "label": "Test7" }, { "value": 10, "label": "Test6" }, { "value": 9, "label": "Test5" }, { "value": 8, "label": "Test4" }, { "value": 7, "label": "Test3" }, { "value": 6, "label": "Test2" }, { "value": 5, "label": "Test1" }, { "value": 4, "label": "TESTG" }, { "value": 3, "label": "Group3" }, { "value": 2, "label": "Group1" } ]
const compareArray = [11, 10, 3, 2]

const sortByObject = compareArray
  .reduce((obj, item, index) => {
    return {
      ...obj,
      [item]: index,
    };
  }, {});

const customSort = options.sort((a, b) => sortByObject[a.value] - sortByObject[b.value]);

It does not sort correctly. The output should be:

[ { "value": 11, "label": "Test7" }, { "value": 10, "label": "Test6" }, { "value": 3, "label": "Test5" }, { "value": 2, "label": "Test4" }, { "value": 9, "label": "Test3" }, { "value": 8, "label": "Test2" }, { "value": 7, "label": "Test1" }, { "value": 6, "label": "TESTG" }, { "value": 5, "label": "Group3" }, { "value": 4, "label": "Group1" } ]

What I'm I doing wrong? It looks it is sorting 11 way down to 2. Which is not what I want.

nhatimme
  • 383
  • 3
  • 19
  • 1
    IMO this is not duplicated because in this case `compareArray.length < options` and using sort will not return what OP is expecting. Here is a version using splice https://jsbin.com/jewuqekuho/edit?html,js,console,output – Arnau Sep 02 '22 at 14:02
  • 1
    This worked perfectly. It is not duplicated as I have a very different problem. Thanks for your help! – nhatimme Sep 02 '22 at 14:14

0 Answers0