Can someone assist me with transforming an array into an object and counting the duplicates of each size? I am hoping to achieve a result like this:
{
"BLACK": {
"XXS": 1,
"M": 1,
"L": 1,
"XL": 2 "},
"WHITE": {
"XXS": 1,
...
}
I attempted to solve this using reduce and split, but the outcome was not as expected:
const products = ["black-XXS", "black-M", "black-L", "black-XL", "black-XL", "white-XXS", "white-L", "red-M "," blue-2XL "," blue-2XL "," blue-2XL "]
var result = products.reduce ((prev, cur) => {
color = cur.split ("-") [0]
size = cur.split ("-") [1]
// prev [size] = (prev [size] || 0) + 1
previous [color] = {[size]: ([size] || 0) + 1}
// prev [color] = {[size]: (prev [size] || 0) + 1}
// {[color] = {[size]: ([size] || 0) + 1}}
// console.log (previous)
return prev;
}, {});
Result = {"black": {"XL": "XL1"}, "white": {"L": "L1"}, "red": {"M": "M1"}, "blue": { "2XL": "2XL1"}}