0

I have an array of objects which looks like this:

[
    {network: "linkedin", visits: 25}
    {network: "twitter", visits: 45}
    {network: "linkedin", visits: 26}
    {network: "twitter", visits: 27}
    {network: "facebook", visits: 235}
    {network: "twitter", visits: 744}
]

I want to return a new array that combines the visits where the network is the same, so the result would be:

[
    {network: "linkedin", visits: 51}
    {network: "twitter", visits: 771}
    {network: "facebook", visits: 235}
]

How can I do this in pure JS? My project also has the Lodash library available, which may also offer a solution.

EDIT: The accepted answer in the duplicate question worked for me.

Matt Saunders
  • 4,073
  • 7
  • 33
  • 47
  • 2
    Please take the [tour] and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Do your research, [search](/help/searching) for related topics on SO, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. Good luck! – T.J. Crowder Apr 20 '18 at 12:56

1 Answers1

0

const inputData = [
  {network: "linkedin", visits: 25},
  {network: "twitter", visits: 45},
  {network: "linkedin", visits: 26},
  {network: "twitter", visits: 27},
  {network: "facebook", visits: 235},
  {network: "twitter", visits: 744}
];

const outputData = inputData.reduce((currentArr, nextObj) => {
  return currentArr.reduce((curr, next) => (next.network === nextObj.network) || curr, false)
    ? currentArr.map((val) => val.network === nextObj.network 
      ? Object.assign({}, val, { visits: val.visits + nextObj.visits }) 
      : val
    )
    : [].concat(currentArr, nextObj);
}, []);

console.log(outputData);
th3n3wguy
  • 3,649
  • 2
  • 23
  • 30
  • This is overkill. With reduce and Object.values is simply enough. – Ele Apr 20 '18 at 13:12
  • @Ele => It might be overkill, but it solves the problem that was asked. – th3n3wguy Apr 20 '18 at 13:15
  • `const outputData = Object.values(inputData.reduce((a, {network, visits}) => { (a[network] || (a[network] = {network, visits: 0})).visits += visits; return a; }, {}));` – Ele Apr 20 '18 at 13:21
  • Your approach is looping too much and that function `map` is the main overkilling logic. – Ele Apr 20 '18 at 13:22
  • @Ele => Your solution doesn't output the data in the same format as the OP requested. Yours outputs an array of values, not the object structure that OP was requesting. – th3n3wguy Apr 23 '18 at 14:07
  • Check carefully, my approach returns the desired output. – Ele Apr 23 '18 at 15:27
  • @Ele => You are correct. That is my mistake. Again, I'm not saying that mine was the most-performant or the best answer, just that it is technically an answer. :D – th3n3wguy Apr 23 '18 at 17:55