lodash groupBy Example

David Zhao
3 min readJul 22, 2021

--

lodash⁴.17.21, groupBy, React¹⁷.0.2, Created at July 21, 2021, Read Series…

Lodash ^4.17.21 makes JavaScript easier by taking the hassle out of working with arrays, numbers, objects, strings, etc. Lodash’s modular methods are great for:
- Iterating arrays, objects, & strings
- Manipulating & testing values
- Creating composite functions

npm i --save lodash

Basic-1.10.1. lodash groupBy commit is here
[Try to understand] groupBy should be handled in web service.

Added GroupedTodo model in src/models/Todo.ts

[Try to understand] GroupedTodo and relation to Todo.

export interface Todo {
id: string,
completed: boolean
text: string,
}
export function createTodoDefault(): Todo {
return {
id: 0,
text: '',
completed: false,
} as unknown as Todo;
}
// added GroupedTodo model
export interface GroupedTodo {
key: string,
items: Todo[]
}

Added GroupedTodo model in src/models/Todo.ts

[Try to understand] _.chain(…).groupBy(…).map(…)
[Try to understand] .groupBy: key=item.id.substr(-1)
is the rightest letter of id field of an item
[Try to understand] .map: map groupBy result to GroupedTodo model

import { useEffect, useState } from 'react';
import { Accordion, AccordionDetails, AccordionSummary, Checkbox, makeStyles, Typography } from '@material-ui/core';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import { ExpandMore } from '@material-ui/icons';
import { GroupedTodo } from 'src/models/Todo';
import _ from "lodash";
const useStyles = makeStyles((theme) => ({
root: {
width: '100%',
},
heading: {
fontSize: theme.typography.pxToRem(15),
fontWeight: theme.typography.fontWeightRegular,
},
}));
export default function ListWithReactFetch(): JSX.Element {
const classes = useStyles();
const [groupedTodoList, setGroupedTodoList] = useState<GroupedTodo[]>([]);
useEffect(() => {
fetch(process.env.REACT_APP_TODOLIST_DATAFILE_URL).then(response => response.json()).then(result => {
const groupedResult = _.chain(result)
.groupBy((item) => {
return item.id.substr(-1);
})
.map((value, key) => ({ key, items: value })).value();
setGroupedTodoList(groupedResult);
// console.log(groupedResult);
});
// console.log('component mounted!')
}, [])
return (
<div className={classes.root}>
<Accordion>
<AccordionSummary
expandIcon={<ExpandMore />}
aria-controls="panel2a-content"
id="panel2a-header"
>
<Typography>Basic 1.10.1. lodash groupBy "last digit of id field"</Typography>
</AccordionSummary>
{groupedTodoList && groupedTodoList.map((item: GroupedTodo) => {
return (
<AccordionDetails key={item.id}>
<div className={classes.root}>
<Accordion>
<AccordionSummary
expandIcon={<ExpandMore />}
aria-controls="panel2a-content"
id={"panel2a-header" + item.key}
>
<Typography>GroupBy: {item.key}</Typography>
</AccordionSummary>
<AccordionDetails>
<TableContainer component={Paper}>
<Table aria-label="simple table">
<TableHead>
<TableRow>
<TableCell>id</TableCell>
<TableCell align="right">
completed
</TableCell>
<TableCell align="right">
text
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{item.items.map((todoItem) => (
<TableRow key={todoItem.id}>
<TableCell component="th" scope="row">
{todoItem.id}
</TableCell>
<TableCell align="right">
<Checkbox
checked={todoItem.completed}
name="checkedB"
color="primary"
/></TableCell>
<TableCell align="right">
{todoItem.text}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
</AccordionDetails>
</Accordion>
</div>
</AccordionDetails>
)
})}
</Accordion>
</div>
);
}

Github commits is here: Basic-1.10.1. lodash groupBy

Conclusion

groupBy is one of key features missing in ES5. Example of lodashgroupBy provided in this article.

You need a groupBy model to contain data if you want strong type in Typescript.

lodash is one of the most popular javascript utility npm packages, with a lot of features, not only groupBy. Chose lodash because popularity and ease-to-use.
Some alternatives: e.g. underscore, ramda

--

--

David Zhao

Expert on .Net, React, React Native . Professional on Asp.Net Mvc/Web Api, C#, React, Typescript, Maui, Html, Css, Sql Server/Oracle.