Languages

JavaScript - sort collection based on external array using lodash

0 points
Asked by:
Laylah-Walsh
654

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
Answered by:
Laylah-Walsh
654

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

  1. Lodash Documentation - _.sortBy()
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join