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
JavaScript
x
3
1
edition = [6, 6, 6, 1, 1, 2];
2
const [groupedEdition, setGroupedEdition] = useState([{"0": 0, "1": 0, "2": 0, "3": 0, "4": 0, "5": 0, "6": 0}]);
3
but I can’t do the function for the set of values
JavaScript
1
4
1
{edition.map((prodotto) => {
2
setGroupedEdition({groupedEdition, XXXX});
3
})}
4
I am expecting this
JavaScript
1
2
1
groupedEdition = {"0": 0, "1": 2, "2": 0, "3": 0, "4": 0, "5": 1, "6": 3}
2
Can you help me? Thank you very much
Advertisement
Answer
You can use reduce()
JavaScript
1
9
1
const edition = [6, 6, 6, 1, 1, 2];
2
const initialValue = {"0": 0, "1": 0, "2": 0, "3": 0, "4": 0, "5": 0, "6": 0};
3
4
const groupedEdition = edition.reduce((acc, item) => {
5
acc[item] += 1;
6
return acc;
7
}, initialValue);
8
console.log(groupedEdition);
9