-2

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?

viraj mane
  • 11
  • 1
  • An object is an unordered list of key-value pairs. If you need a defined order then use an array. You could extract the property names, sort them in the order you need and then access the properties in the object in the order of the array. - [Does JavaScript guarantee object property order?](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – Andreas Mar 11 '22 at 08:51

2 Answers2

0

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);
YuTing
  • 6,555
  • 2
  • 6
  • 16
0

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);
viraj mane
  • 11
  • 1