2

I have an array and a set of object. Unable to sort that object by given key.

var a = ['e','a','c','d','b'];
var b = {'d':'12','e':'23','c':'34','b':'45','a':'56'};
var c = {};

for(var i=0; i<a.length; i++){
    for(var j in b){
        if(a[i] == j){
            c[j]=b[j]
        }
    }
}
console.table(c);

enter image description here

clemens
  • 14,173
  • 11
  • 38
  • 52
  • 1
    so you have just the wrong user agent, because in the newer ES2015, objetcs are sorted, but i would not rely on this. – Nina Scholz Jan 05 '18 at 07:03
  • 1
    Possible duplicate of [Sort JavaScript object by key](https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key) – Pyromonk Jan 05 '18 at 07:04
  • Added a screenshot of the console, in console table, it is showing the shorted object but not rendering in that way – Krishna Babu Jan 05 '18 at 07:04
  • please try to iterate through the "sorted" object without taking the console view. this could have an own mapper for the order of object's keys. – Nina Scholz Jan 05 '18 at 07:25

2 Answers2

0

It is a key-value mapping. Maintaining order in which keys are inserted defeats the benefit of O(1) insertion time.

Why would you want to sort it? If required its better to maintain an array of key-value pairs and sort them to use later. For your case,

arr = [["orange", 10],["appple", 5], ["banana", 20], ["cherry", 13]];

Use a custom sort function as

arr.sort = function(a,b) {
    return a[1]>b[1]? 1:a[1]<b[1]?-1:0;
}

Apply sort,

keysArr.sort() Traverse sorted keysArr and use elements that as a key to retrieve value.

0

Is this something you are looking for.

var a = ['e','a','c','d','b'];
var b = {'d':'12','e':'23','c':'34','b':'45','a':'56'};
var c = {};

a.forEach((val) => {
 c[val] = b[val];
});

console.log(c)
Mukesh
  • 860
  • 1
  • 9
  • 20