简体   繁体   中英

Sort an array of objects with random values

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

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)

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]
})

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