EN
JavaScript - sort collection based on external array using lodash
1
answers
0
points
How can I sort collection based on external array using lodash?
Let's say I have the following array of values:
var values = ['value1', 'value2', 'value3', 'value4'];
and array of objects:
var objects = [
{ id: 'value2', name: 'Tom' },
{ id: 'value4', name: 'Kate' },
{ id: 'value1', name: 'Ann' },
{ id: 'value3', name: 'Mark' }
];
Now, is there any way to sort the array of objects based on the order of values in the first array?
The result I want to get is:
[
{ id: 'value1', name: 'Ann' },
{ id: 'value2', name: 'Tom' },
{ id: 'value3', name: 'Mark' },
{ id: 'value4', name: 'Kate' }
]
1 answer
0
points
You can use lodash _.sortBy() method with a custom compare function to sort the array of objects in order of the other array values.
Practical example
In this example, we use lodash cdn to provide lodash library.
// 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>
var values = ['value1', 'value2', 'value3', 'value4'];
var objects = [
{ id: 'value2', name: 'Tom' },
{ id: 'value4', name: 'Kate' },
{ id: 'value1', name: 'Ann' },
{ id: 'value3', name: 'Mark' }
];
var sortedCollection = _.sortBy(objects, function(object) {
return values.indexOf(object.id);
});
console.log(JSON.stringify(sortedCollection, null, 4)); // [ 2, 3, 3 ]
</script>
</body>
</html>
References
0 comments
Add comment