diff --git a/bun.lockb b/bun.lockb
index c0eb840..eb04c75 100755
Binary files a/bun.lockb and b/bun.lockb differ
diff --git a/components/Infographic.tsx b/components/Infographic.tsx
index a9bf416..04a236b 100644
--- a/components/Infographic.tsx
+++ b/components/Infographic.tsx
@@ -3,6 +3,7 @@
import { useState } from "react";
import dynamic from "next/dynamic";
import { ChartData, ChartOptions } from "chart.js";
+import { getUniqueMonths } from "@/lib/getUniqueMonths";
import { stringToUniqueColour } from "@/lib/stringToUniqueColour";
import { transformDataToDatasets } from "@/lib/transformDataToDatasets";
import type { Car, ChartDataset, Dataset } from "@/types";
@@ -25,7 +26,7 @@ export const Infographic = ({ electricCars }: InfographicProps) => {
const [datasets, setDatasets] = useState(initialDatasets);
const data: ChartData<"line"> = {
- labels: [...new Set(electricCars.map(({ month }) => month))],
+ labels: getUniqueMonths(electricCars),
datasets: datasets.filter(({ checked }) => checked),
};
@@ -94,8 +95,8 @@ export const Infographic = ({ electricCars }: InfographicProps) => {
return (
{
+ it("should return a unique set of dates", () => {
+ const dates = [
+ { key: "2023-04" },
+ { key: "2023-04" },
+ { key: "2023-04" },
+ { key: "2023-01" },
+ { key: "2023-02" },
+ { key: "2023-03" },
+ ];
+
+ const result = ["2023-01", "2023-02", "2023-03", "2023-04"];
+
+ expect(getUniqueMonths(dates, "key")).toHaveLength(4);
+ expect(getUniqueMonths(dates, "key")).toEqual(result);
+ });
+});
diff --git a/lib/getUniqueMonths.ts b/lib/getUniqueMonths.ts
new file mode 100644
index 0000000..9c1e5ba
--- /dev/null
+++ b/lib/getUniqueMonths.ts
@@ -0,0 +1,9 @@
+import { parseISO } from "date-fns";
+
+export const getUniqueMonths = (data: any[], sortKey: string = "month") =>
+ [...new Set(data.map((item) => item[sortKey]))].sort((a, b) => {
+ const monthA = parseISO(a);
+ const monthB = parseISO(b);
+
+ return monthA.getTime() - monthB.getTime();
+ });
diff --git a/package.json b/package.json
index c72803e..919b28a 100644
--- a/package.json
+++ b/package.json
@@ -14,6 +14,7 @@
"chart.js": "^4.4.0",
"classnames": "^2.3.2",
"d3": "^7.8.5",
+ "date-fns": "^2.30.0",
"next": "14.0.0",
"react": "^18",
"react-chartjs-2": "^5.2.0",