1

i was coding and i found this problem, the goal is turn the items array into a object with property key/value, counting the items that appear more than once like that:

{
  cookie:{
    MILK: 1,
    CHOCOLATE: 2,
    DELUXE: 1
  },
  bread:{
    BIG: 2
  },
  beer:{
    NEW: 1,
    OLD: 1
  }
}

I tried this code below

const items = [
  "cookie-MILK",
  "cookie-CHOCOLATE",
  "cookie-CHOCOLATE",
  "cookie-DELUXE",
  "bread-BIG",
  "bread-BIG",
  "beer-NEW",
  "beer-OLD"
]
let newArray = [];

items.forEach((e) => {
  let splitArray = e.split("-");
  newArray.push([splitArray[0], splitArray[1]]);
});


let result = newArray.reduce((acc, val) => {
  if (!acc[val[0]] && !acc[val[1]] ) acc[val[0]] = {
     [val[1]]: 1,
  };
   else acc[val[0]][val[1]]++;
  return acc;
}, {});

But this code returns it and i don't know how to solve this question

{
  cookie:{
    MILK: 1,
    CHOCOLATE: NaN,
    DELUXE: NaN
  },
  bread:{
    BIG: 2
  },
  beer:{
    NEW: 1,
    OLD:  NaN
  }
}

2 Answers 2

3

You could take a logical nullish assignment ??= for assigning an object or zero and increment the value.

const
    items = ["cookie-MILK", "cookie-CHOCOLATE", "cookie-CHOCOLATE", "cookie-DELUXE", "bread-BIG", "bread-BIG", "beer-NEW", "beer-OLD"],
    result = items.reduce((acc, val) => {
        const [left, right] = val.split("-");
        (acc[left] ??= {})[right] ??= 0;
        acc[left][right]++;
        return acc;
    }, {});

console.log(result);

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

Comments

2

I think is beter solution:

const items = [
  "cookie-MILK",
  "cookie-CHOCOLATE",
  "cookie-CHOCOLATE",
  "cookie-DELUXE",
  "bread-BIG",
  "bread-BIG",
  "beer-NEW",
  "beer-OLD"
];

let res = {};
items.forEach(item => {
    let itemParsed = item.split("-");
    if(typeof res[itemParsed[0]] == "undefined")
        res[itemParsed[0]] = {}
    
    if(typeof res[itemParsed[0]][itemParsed[1]] == "undefined")
        res[itemParsed[0]][itemParsed[1]] = 0;

    res[itemParsed[0]][itemParsed[1]]++;
})

console.log(res)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.