M
M
mamaanarhiya2018-02-14 14:47:39
JavaScript
mamaanarhiya, 2018-02-14 14:47:39

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}]

You need to sort it by key elements, but not just by greater or lesser, but specifically you need to go first with key = 15, then with key = 24, then with key = 17 and last with key = 18. It is not necessary that all there are objects in the array, that is, there may be such an array [{value: 1232312, key: 17}, {value: 123, key: 15}].

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Interface, 2018-02-14
@mamaanarhiya

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))

V
Vladimir, 2018-02-14
@Casufi

https://developer.mozilla.org/en-US/docs/Web/JavaS...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question