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.