简体   繁体   中英

sort object by given key value sequence in javascript

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);

在此处输入图片说明

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM