If you are sure that there will only be one key in each object, and all you are wanting to sort by is the value, here's how you can do that:
var array = [{fgy : 34}, {sor : 56}, {dtr : 45}];
let sorted = array.slice().sort((a,b) => {
let aVal = Object.values(a)[0];
let bVal = Object.values(b)[0];
return aVal - bVal;
});
console.log(sorted)
If multiple keys can be on each object, you just need to decide what you are sorting on and use that for your aVal
and bVal
in the .sort()
function. For example, if you wanted to sort by the maximum value, you could do something like let aVal = Math.max(...Object.values(a));
, similarly, you could do the sum of the values, minimum value, etc. You just need to assign a value to your aVal
and bVal
and then return the comparison.
ES5 syntax version (as requested in comments)
var array = [{fgy : 34}, {sor : 56}, {dtr : 45}];
let sorted = array.slice().sort((a,b) => {
var aVal = a[Object.keys(a)[0]];
var bVal = b[Object.keys(b)[0]];
return aVal - bVal;
});
console.log(sorted)