I have an array of integers from 0 to 6 as input I need to return an object with the count of each of those numbers
edition = [6, 6, 6, 1, 1, 2]; const [groupedEdition, setGroupedEdition] = useState([{"0": 0, "1": 0, "2": 0, "3": 0, "4": 0, "5": 0, "6": 0}]);
but I can’t do the function for the set of values
{edition.map((prodotto) => { setGroupedEdition({...groupedEdition, XXXX}); })}
I am expecting this
groupedEdition = {"0": 0, "1": 2, "2": 0, "3": 0, "4": 0, "5": 1, "6": 3}
Can you help me? Thank you very much
Advertisement
Answer
You can use reduce()
const edition = [6, 6, 6, 1, 1, 2]; const initialValue = {"0": 0, "1": 0, "2": 0, "3": 0, "4": 0, "5": 0, "6": 0}; const groupedEdition = edition.reduce((acc, item) => { acc[item] += 1; return acc; }, initialValue); console.log(groupedEdition);