Languages

JavaScript - sorting array of objects in specific order (using existing lodash function)

0 points
Asked by:
JoanneSenior
1070

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
Answered by:
JoanneSenior
1070

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

  1. Lodash Documentation - _.sortBy()
  2. Lodash Documentation - _.indexOf()
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