In this my project, I have an array of objects where I'm to get the unique values so i can use the unique values as a checkbox label. Now, that works fine but the problem now is that I needed to get the numbers of occurrence in front of the values. I can't get this at the moment because the values now returns only the unique values using the Set method. Form example.. I want to have something like 2021-10-25(3) 2021-10-18(1) 2021-10-04(2).
link to replit replitlink
Here is my App.js code
import "./styles.css";
import React, { useEffect, useState, useRef } from "react";
export default function App() {
const Defaultdata = [
{
date_listed: "4 hours ago",
id: "7857699961",
delivery_time_frame: "2021-10-25 - 2021-11-14",
distance: "22.8 km",
time_stamp: "2021-10-25 16:36:54",
watched: "yes"
},
{
date_listed: "3 days ago",
id: "8358962006",
delivery_time_frame: "2021-10-18 - 2021-10-24",
distance: "4.3 km",
time_stamp: "2021-10-22 16:54:12"
},
{
date_listed: "4 hours ago",
delivery_id: "8146462294",
delivery_time_frame: "2021-10-25",
distance: "4.3 km",
time_stamp: "2021-10-25 16:12:32"
},
{
date_listed: "4 hours ago",
delivery_id: "8146462294",
delivery_time_frame: "2021-10-04 - 2021-11-14",
distance: "4.3 km",
time_stamp: "2021-10-25 16:12:32"
},
{
date_listed: "4 hours ago",
delivery_id: "8146462294",
delivery_time_frame: "2021-10-25 - 2021-10-31",
distance: "4.3 km",
time_stamp: "2021-10-25 16:12:32"
},
{
date_listed: "4 hours ago",
delivery_id: "8146462294",
delivery_time_frame: "2021-10-04 - 2021-11-14",
distance: "4.3 km",
time_stamp: "2021-10-25 16:12:32"
}
];
return (
<div className="App">
{[
...new Set(Defaultdata.map((a) => a.delivery_time_frame.substr(0, 10)))
].map((dates, i) => (
<label style={{ listStyle: "none" }} key={i}>
<input
type="checkbox"
value={dates}
/>
<span>{dates}({dates.length})</span>
</label>
))}
</div>
);
}
You can first create a hook useFilteredValuesAndCounts which will return an object that contain dataSet and countObj.
1) dataSet will contain unique dates
2) countObj is an object which contain occurrence of each date
Live Demo
function useFilteredValuesAndCounts(arr) {
const countObj = {};
const set = new Set();
arr.forEach((a) => {
const date = a.delivery_time_frame.substr(0, 10);
countObj[date] = (countObj[date] ?? 0) + 1;
set.add(date);
});
return { dataSet: [...set], countObj };
}
export default useFilteredValuesAndCounts;
and in JSX you can simply use as:
const { dataSet, countObj } = useFilteredValuesAndCounts(Defaultdata);
return (
<div className="App">
{dataSet.map((dates, i) => (
<label style={{ listStyle: "none" }} key={i}>
<input type="checkbox" value={dates} />
<span>
{dates}({countObj[dates]})
</span>
</label>
))}
</div>
);