Search code examples
javascriptjavascript-objects

Reverse order of object values while maintaining order of keys


I have the following object...

{0: "#000000", 1: "#FFFFFF", 0.292: "#ff0000", 0.7: "#3498db"}

How can reverse the order of the hex values respective to their keys? This is what I want to achieve...

{0: "#FFFFFF", 0.292: "#3498db", 0.7: "#ff0000", 1: "#000000"}

Solution

  • function reverseValues(original) {
      // put into a combination array
      var combined = [];
      for (var key in original) {
        // note: keys are always strings! So use +key to convert to a number for sorting
        combined.push({key: +key, val: original[key]});
      }
    
      // sort it by the key value
      combined.sort((a, b) => a.key - b.key);
    
      // Create the result
      var result = {};
      var combinedMax = combined.length - 1;
      combined.forEach((kv, i) => result[kv.key] = combined[combinedMax - i].val);
      return result;
    }
    
    var testVal = {0: "#000000", 1: "#FFFFFF", 0.292: "#ff0000", 0.7: "#3498db"};
    console.dir(reverseValues(testVal));