Search code examples
javascriptarraysobjectlodash

Sort object keys with a sorted array


I have the below code that sorts object in an alphabetic order, I want to get away from having an alphabetic order and sort on my own chosen order.

var obj = {
  c: "see",
  a: "ay",
  b: "bee",
  d: "dee"
};

console.log("Object order:");
var key, keys = [];
for (key in obj) {
  keys.push(key);
}
console.log(keys.map(function(key) { return key + ": " + obj[key];}).join(", "));

console.log("Sorted order:");
keys = Object.keys(obj).sort()
console.log(keys.map(function(key) { return key + ": " + obj[key];}).join(", "));

The above will output the object order of a, b, c, d - but lets say I want an array to have my own order e.g.

var sortedArray = ['b','c','d','a'];

So how do I know implement this sortedArray into my .sort?

Expected outcome:

var newObj = {
  b: "bee",
  c: "cee",
  d: "dee",
  a: "ay"
};

Thanks


Solution

  • It's a very weird pattern to a sort, but as you want, I made a function called CustomOrderBy which will do a sort based on an array of keys.

    Something like this:

    1. You have an array with the keys you want ordered from first to last, like you already have (sortedArray). Then you pass this array to the function.

    2. The function then loop through the obj keys and get the first letter of it to check if it matches with the arra of keys, getting its index. Based on the index, it sorts.

    3. After the sort, then it creates a new obj and set the key and the value in the order it created in the sort function used before

    Please, see the code to undertand it better.

    var sortedArray = ['b', 'c', 'd', 'a'];
    
    var obj = {
      c: "see",
      a: "ay",
      b: "bee",
      d: "dee"
    };
    
    function CustomOrderBy(keyOrder){
      let keysSorted = Object.keys(obj).sort(function(keyA, keyB) {
        let idxA = keyOrder.indexOf(keyA[0]);  
        let idxB = keyOrder.indexOf(keyB[0]);
        if (idxA > idxB){
          return 1
        }else if(idxA < idxB){
          return -1
        }else{
          return 0;
        }  
      });
    
      let sorted = {};
      for (var key of keysSorted){
        if (obj[key] != null){
          sorted[key] = obj[key];
        }
      }
      return sorted;
    }
    console.log(CustomOrderBy(sortedArray))