Reputation: 17
total newbie here. I need to sort array of random objects (to pass data to machine I build). How to do that?
var array = [{fgy : 34}, {sor : 56}, {dtr : 45}];
array.sort(function(a, b){return a- b;});
// ofcourse it is not working
Expected result:
fgy : 34, dtr : 45, sor : 56
Upvotes: 0
Views: 710
Reputation: 11116
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.
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)
Upvotes: 3
Reputation: 3
You can use the Array.sort method, But you need to get the value inside each Object in the array.
You can do it using Object.values(obj)[0]
.
Which will return the first value in the object
For example:
let obj = { fgy: 34 }
console.log(Object.values(obj)[0]) // returns 34
Then you can use it with the sort method:
array.sort((a, b) => {
return Object.values(a)[0] - Object.values(b)[0]
})
Upvotes: 0