EN
JavaScript - sorting array of objects in specific order (using existing lodash function)
1 answers
0 points
How can I sort array of objects in a specific, custom order?
I have the following array:
xxxxxxxxxx
1
const array = [
2
{ key: 'a', value: 20 },
3
{ key: 'd', value: 30 },
4
{ key: 'c', value: 10 },
5
{ key: 'b', value: 40 },
6
];
and I want it to be sorted in the following order by key value:
xxxxxxxxxx
1
['c', 'a', 'd', 'b']
so the result would be:
xxxxxxxxxx
1
[
2
{ key: 'c', value: 10 },
3
{ key: 'a', value: 20 },
4
{ key: 'd', value: 30 },
5
{ key: 'b', value: 40 }
6
]
How can I do this?
1 answer
0 points
You can do it simply using lodash.
Practical examples
1. Full running example using lodash cdn:
xxxxxxxxxx
1
2
<html>
3
<head>
4
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
5
</head>
6
<body>
7
<script>
8
9
const array = [
10
{ key: 'a', value: 20 },
11
{ key: 'd', value: 30 },
12
{ key: 'c', value: 10 },
13
{ key: 'b', value: 40 },
14
];
15
16
const customOrder = ['c', 'a', 'd', 'b'];
17
18
const result = _.sortBy(array, (obj) => _.indexOf(customOrder, obj.key));
19
20
console.log(JSON.stringify(result, null, 4));
21
22
</script>
23
</body>
24
</html>
2. Working with Node.js:
xxxxxxxxxx
1
const _ = require('lodash');
2
3
const array = [
4
{ key: 'a', value: 20 },
5
{ key: 'd', value: 30 },
6
{ key: 'c', value: 10 },
7
{ key: 'b', value: 40 },
8
];
9
10
const customOrder = ['c', 'a', 'd', 'b'];
11
12
const result = _.sortBy(array, (obj) => _.indexOf(customOrder, obj.key));
13
14
console.log(JSON.stringify(result));
References
0 commentsShow commentsAdd comment