Answer the question
In order to leave comments, you need to log in
How to sort the data in an array?
I have an array with the following data:
[{value: 123, key: 15},{value: 321, key: 18},{value: 1232312, key: 17},{value: 5678, key: 24}]
Answer the question
In order to leave comments, you need to log in
Create an array or object that "maps" key to its order in the queue. And use the map in the sort method of the array:
const keySortPriorities = [15, 24, 17, 18];
[{value: 1232312, key: 17}, {value: 123, key: 15}]
.sort((a, b) => keySortPriorities.indexOf(a.key) - keySortPriorities.indexOf(b.key));
[{value: 123, key: 15},{value: 321, key: 18},{value: 1232312, key: 17},{value: 5678, key: 24}]
.sort((a, b) => keySortPriorities.indexOf(a.key) - keySortPriorities.indexOf(b.key))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question