Change The Order Of _.groupBy() Result Data
Solution 1:
The property order for objects in ES6 is:
- The keys that are integer indices, in ascending numeric order.
- Then, all other string keys, in the order in which they were added to the object.
- Lastly, all symbol keys, in the order in which they were added to the object.
The output object has integer keys. No matter which order you insert the keys to the object, it will always be printed in the order: 10 -> 12 -> 13
You could use a Map
as an output. Map
objects hold key-value pairs and remember the original insertion order of the keys
Create an object with each unique siteID
as key and an array with single object as value. Then sort
the entries of the object based on the name
of each object. Then create a Map
from these sorted entries (Check the browser's console for the output. Stack snippets displays Map
as an empty object)
let data = [
{"name": "ragupathi", "siteID": 10},
{"name": "abi", "siteID": 13},
{"name": "abi","siteID": 13},
{"name": "mahesh", "siteID": 12},
{"name": "abi", "siteID": 13},
{"name": "abi", "siteID": 13},
{"name": "ragupathi", "siteID": 10}
]
const uniqueSiteGroups = {};
data.forEach(o => uniqueSiteGroups[o.siteID] = [o])
const sortedEntries = Object.entries(uniqueSiteGroups)
.sort((a, b) => a[1][0].name.localeCompare(b[1][0].name))
const map = new Map(sortedEntries)
console.log(map) // check the browser's console
Solution 2:
Since order of the props is not guaranteed you have to utilize Map or other methods to get the sorting and the output you need.
You can use Array.sort, Array.forEach and Map like this:
let data = [{"name": "ragupathi", "siteID": 10},{"name": "abi", "siteID": 13},{"name": "abi","siteID": 13},{"name": "mahesh", "siteID": 12},{"name": "abi", "siteID": 13},{"name": "abi", "siteID": 13},{"name": "ragupathi", "siteID": 10}],
map = new Map()
data
.sort((a,b) => b.siteID - a.siteID)
.forEach(x => map.set(x.siteID, [...(map.get(x.siteID) || []), x] || [x]))
console.log(map) // The map object output in your browser console
console.log(Array.from(map.values())) // The siteIds in array form
Once you have them in the map
object then you can access the groups easily by siteID
like map.get(13)
and you will get the array of the grouped items for the siteID of 13.
You can also always get the order in which you have stored the keys in the map via the Map.keys() method.
Post a Comment for "Change The Order Of _.groupBy() Result Data"