1

I need help, I want to transform the array into an object and count the duplicates of each size and I hope it brings this result:

{
    "BLACK": {
    "XXS": 1,
    "M": 1,
    "L": 1,
    "XL": 2 "},
    "WHITE": {
    "XXS": 1,
    ...
}

I tried to use reduce and split, but it returns like this:

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"}}

2 Answers 2

2

You need to explicitly create the outer object first if it doesn't exist yet, as a separate statement. Then you can increment the possibly-existing size property on it:

const products = ["black-XXS", "black-M", "black-L", "black-XL", "black-XL", "white-XXS", "white-L", "red-M "," blue-2XL "," blue-2XL "," blue-2XL "]

const productsByColor = {};
for (const product of products) {
  const [color, size] = product.toUpperCase().split('-');
  if (!productsByColor[color]) {
    productsByColor[color] = {};
  }
  productsByColor[color][size] = (productsByColor[color][size] || 0) + 1;
}
console.log(productsByColor);

Sign up to request clarification or add additional context in comments.

Comments

0

I did it a bit differently but CertainPerformance is right you need to define your empty Object first. I would also suggest that you make sure that every element in your array follow a similar format. For example there are white spaces inside the " blue-2XL " string.

Here is how I would do it:

const products = ["black-XXS", "black-M", "black-L", "black-XL", "black-XL", "white-XXS", "white-L", "red-M", "blue-2XL", "blue-2XL", "blue-2XL"]

const hash = {};
products.forEach(item => {
    let color = item.split("-")[0];
    let size = item.split("-")[1];
    if(!hash[color]) {hash[color] = {}};
    if(!hash[color][size]) {hash[color][size] = 1} else {hash[color][size] = hash[color][size] + 1};
});

If you console.log(hash); you should have:

{ black: { XXS: 1, M: 1, L: 1, XL: 2 },
white: { XXS: 1, L: 1 },
red: { M: 1 },
blue: { '2XL': 3 } }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.