I have an array that has several other arrays inside it. All data is already sorted alphabetically.
What I would like to know is how can I group alphabetically?
Just like in the example image below:
Here's my project I put into codesandbox
import "./styles.css";
import { data } from "./data";
export default function App() {
console.log("data: ", data);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
{data.map((item, index) => (
<div key={index}>
{item.map((item2, index2) => (
<div key={index2}>
<span>{item2.title}</span>
</div>
))}
</div>
))}
</div>
);
}
Thank you in advance for any help!!!
TL;DR. See the Code Sandbox I cloned and edited from yours.
In summary, I did something like below:
import "./styles.css";
import { data } from "./data";
export default function App() {
// Flatten `data` array
const merged = [];
data.map((arr) => arr.map((item) => merged.push(item)));
// Reduce `merged` array by initial character of `title`
const mapped = merged.reduce((acc, item) => {
const letter = item.title[0].toLowerCase();
if (!acc[letter]) {
acc[letter] = [];
}
acc[letter].push(item);
return acc;
}, {});
const letters = Object.keys(mapped);
return (
<div className="App">
<h1>Grouped by the first initial</h1>
{letters.map((letter, i) => (
<div key={i}>
<h2>{letter}</h2>
{mapped[letter].map((item, j) => (
<div key={j}>{item.title}</div>
))}
</div>
))}
</div>
);
}
data array into merged variable.merged into a dictionary-like object (by each first initial) into mapped variable.mapping the merged array.See it in action in the Code Sandbox.