Daniel Passos
Daniel Passos

Reputation: 15

JS Turn an array into Object with property key/value

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

Upvotes: 1

Views: 48

Answers (2)

Bahador Raghibizadeh
Bahador Raghibizadeh

Reputation: 1265

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)

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386868

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);

Upvotes: 3

Related Questions