Home > Software engineering >  how do I sort object by first element in value list
how do I sort object by first element in value list

Time:03-11

I have javascript object like this,

var list = {
  "you": [100,'x',67],
  "me": [456,'xxx',68],
  "foo": [7856,'yux',69],
  "bar": [2,'xcv',45]
};

I am trying to sort it according to the first element in the value list. like this

var list = {
    "foo": [7856,'yux',69],
    "me": [456,'xxx',68],
    "you": [100,'x',67],
    "bar": [2,'xcv',45],
};

I couldn't find any resources, with similar implementation in java script.

can anyone help?

CodePudding user response:

I totally agree with @Andreas about Does JavaScript guarantee object property order? . But maybe an array output is what you expect.

var list = {
  "you": [100,'x',67],
  "me": [456,'xxx',68],
  "foo": [7856,'yux',69],
  "bar": [2,'xcv',45]
};
var arr = [];
for (const [key, value] of Object.entries(list)) {
  arr.push({k:key, v:value})
}
arr = arr.sort((a, b) => b.v[0] - a.v[0])
console.log(arr);

CodePudding user response:

thanks @YuTing for the help.

working solution

var sortable = [];
for (var i in list) {
    sortable.push([i, list[i]])
}

sortable.sort(function(a, b) {
    return b[1][0] - a[1][0];
});

// console.log(sortable);
var objSorted = {}
sortable.forEach(function(item){
    objSorted[item[0]]=item[1]
})

console.log(objSorted);
  • Related