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:
const array = [
{ key: 'a', value: 20 },
{ key: 'd', value: 30 },
{ key: 'c', value: 10 },
{ key: 'b', value: 40 },
];
and I want it to be sorted in the following order by key value:
['c', 'a', 'd', 'b']
so the result would be:
[
{ key: 'c', value: 10 },
{ key: 'a', value: 20 },
{ key: 'd', value: 30 },
{ key: 'b', value: 40 }
]
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:
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
</head>
<body>
<script>
const array = [
{ key: 'a', value: 20 },
{ key: 'd', value: 30 },
{ key: 'c', value: 10 },
{ key: 'b', value: 40 },
];
const customOrder = ['c', 'a', 'd', 'b'];
const result = _.sortBy(array, (obj) => _.indexOf(customOrder, obj.key));
console.log(JSON.stringify(result, null, 4));
</script>
</body>
</html>
2. Working with Node.js:
const _ = require('lodash');
const array = [
{ key: 'a', value: 20 },
{ key: 'd', value: 30 },
{ key: 'c', value: 10 },
{ key: 'b', value: 40 },
];
const customOrder = ['c', 'a', 'd', 'b'];
const result = _.sortBy(array, (obj) => _.indexOf(customOrder, obj.key));
console.log(JSON.stringify(result));
References
0 comments
Add comment