Subscribe
You'll get a notification every time a post gets published here.
Sometimes after data retrieved from the backend, We want to display the data using group by option. Array contains list of object where each object contains multiple keys and values.
There are multiple ways we can achive group by in the array of objects
First, let us declare array of objects, each object holds key and values of
var emps = [
{
name: "frank",
id: 1,
department:"sales"
},
{
name: "john",
id: 2,
department:"hr"
},
{
name: "eric",
id: 3,
department:"sales"
},
{
name: "andrew",
id: 4,
department:"sales"
}];
## using lodash groupBy examples
lodash is popular library which provides lot useful inbuilt utility methods.
This is very easy to implement in the projects
groupBy method takes collection of objects
```html
_.groupBy(collection, [iteratee=_.identity])
input is array of objects and iteratee is property of an object for grouping
following is an example grouping the employee object by department
var emps = [
{
name: "frank",
id: 1,
department:"sales"
},
{
name: "john",
id: 2,
department:"hr"
},
{
name: "eric",
id: 3,
department:"sales"
},
{
name: "andrew",
id: 4,
department:"sales"
}];
_.groupBy(emps, 'department');
And the output returns group of departments
hr: [Object {department: "hr", id: 2, name: "john"}]
sales: [Object {department: "sales", id: 1, name: "frank"}, Object {department: "sales", id: 3, name: "eric"}
EcmaScript
2005 provides array inbuilt method reduce
function. reduce function provides
function groupBy(arrayObjects, key) {
return arrayObjects.reduce(function(result, currentObject) {
const val = currentObject[key]
result[val] = result[val] || []
result[val].push(currentObject)
return result
}, {})
}
and output is
{ sales:
[ { name: 'frank', id: 1, department: 'sales' },
{ name: 'eric', id: 3, department: 'sales' },
{ name: 'andrew', id: 4, department: 'sales' } ],
hr: [ { name: 'john', id: 2, department: 'hr' } ] }
🧮 Tags
Recent posts
Typescript switch case - top examples How to add local jar from local repository in maven projects How to force update dependencies commandline | eclipse| Intelli IDEA Learn Golang Tutorials - if else statement examples Learn Golang Tutorials - Hello World First Program example ExplainedRelated posts