0

Im building a function on Javascript to reduce an array like this:

   var myArray = [
    {sku: "one", price: "3"},
    {sku: "two", price: "5"},
    {sku: "one", price: "2"},
    {sku: "three", price: "3"},
    {sku: "three", price: "9"}
];

to this:

{ one: [ '3', '2' ], two: [ '5' ], three: [ '3', '9' ] }

in order to categorize my skus. It works just fine right now.

 function itemQuantity(data) {

     let group_to_values = data.reduce(function (obj, item) {
        obj[item.sku] = obj[item.sku] || [];
        obj[item.sku].push(item.price);
        return obj;
    }, {});
    return group_to_values;
}

console.log(itemQuantity(myArray));

My issue comes when I try to modify it. instead of having one: [ '3', '2' ] I need the NUMBER of items (or quantity) {one: 2, two: 1...} I trieed to add obj.length but cant make it work!

Please help!

  • `counts` is an object with one property for each "name". `eventst` is an array with length `data.length` that consists of only `undefined` values because `.forEach()` doesn't return anything. – Andreas Feb 08 '21 at 15:36
  • _"How would you approach it?"_ - Search here on SO for _"javascript array of objects group by property"_ and adapt one of the many answers to this usecase. – Andreas Feb 08 '21 at 15:36

0 Answers0