Joe
Joe

Reputation: 4254

Group and sum with underscore

Input:

const data = [
  {
    id: 'RS11',
    name: 'Road 1',
    quantity: {
      lengthVal: 50
    }
  },
  {
    id: 'RS11',
    name: 'Road 1',
    quantity: {
      lengthVal: 100
    }
  },
   {
    id: 'RS11',
    name: 'Road 2',
    quantity: {
      lengthVal: 20
    }
  }
]

Each property except quantity should be grouped. quantity.lengthVal should be summarized. A count property should also be added.

Expected output:

const expected = [
  {
    id: 'RS11',
    name: 'Road 1',
    count: 2,
    summarizedLength: 150
  },
   {
    id: 'RS11',
    name: 'Road 2',
    count: 1,
    summarizedLength: 20
  }
]

This is what i tried:

const groupAndSum = (arr) => {
  return _.chain(arr)
    .groupBy((obj) => {
       // Some reduce here?
       return _.values(_.without(obj), 'quantity').join('|')
    })
    .map((val) => {
       val[0].count = val.length;
       delete val[0].quantity;
       return val[0];
    })
    .value();
}

Jsbin: https://jsbin.com/totujopume/edit?html,js,console

Dataset is quite big so performance is important.

Upvotes: 4

Views: 157

Answers (1)

charlietfl
charlietfl

Reputation: 171689

Can do this with a fairly simple native reduce() that only makes one iteration through the array for whole procedure

const res = Object.values(
  data.reduce((a, c) => {
    const key = c.id + '|' + c.name;
    const o = a[key] = a[key] || c;
    o.count            = (o.count || 0) +1;
    o.summarizedLength = (o.summarizedLength || 0) + c.quantity.lengthVal;
    delete c.quantity;
    return a;
  },{})
);

console.log(res)
.as-console-wrapper {	max-height: 100%!important;}
<script>
  const data = [{
      id: 'RS11',
      name: 'Road 1',
      quantity: {
        lengthVal: 50
      }
    },
    {
      id: 'RS11',
      name: 'Road 1',
      quantity: {
        lengthVal: 100
      }
    },
    {
      id: 'RS11',
      name: 'Road 2',
      quantity: {
        lengthVal: 20
      }
    }
  ]
</script>

Upvotes: 2

Related Questions