Search code examples
javascriptarrayssortinglodash

Sort values by lookup table using Lodash preferably


My data looks like this:

var list = [
{ name:'Charlie', age:3},
{ name:'Dog', age:1 },
{ name:'Baker', age:7},
{ name:'Abel', age:9 },
{ name:'Jim', age:5 }
];

I want to add a custom order e.g. not by numerical value or alphabetical. I am guessing I need to create a lookup table to accomplish my unique order/rank like below.

var rank = [
0: {'Abel'},
1: {'Baker'},
2: {'Jim'},
3: {'Charlie'},
4: {'Dog'}]

const name = _.sortBy(names, list=>{return list.name});

My name should = Abel, as I am only interested who is top. If Abel does not exist then name will bring back Baker etc...

I will probably need to use Lodash sortBy, however open to other clean solution to do it.


Solution

  • You could take a hash table with the wanted value for sorting.

    For unknown names, you could add a default value and moveht these items either to top (smaller than one) or to bottom (Infinity).

    The sort value should be different from zero, because otherwise a default value would not work, because of the falsy nature of zero.

    var list = [{ name: 'Charlie', age:3 }, { name: 'Dog', age: 1 }, { name: 'Baker', age: 7 }, { name: 'Abel', age: 9 }, { name: 'Jim', age: 5 }],
        rank = { Abel: 1, Baker: 2, Jim: 3, Charlie: 4, Dog: 5 },
        ordered = _.sortBy(list, ({ name }) => rank[name]);
    
    console.log(ordered);
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>