1

I have an array as mentioned below:

var somevalue = [{
    code: 1,
    name: 'a1'
  }, {
    code: 2,
    name: 'b1'
  }, {
    code: 1,
    name: 'a2'
  },
  {
    code: 1,
    name: 'a3'
  },
  {
    code: 2,
    name: 'b2'
  }
]

From this array, I want to find duplicate element by code and merge all elements of the same code into one. So the final output would be:

var somevalue = [{
    code: 1,
    name: 'a1, a2'
  }, {
    code: 2,
    name: 'b1, b2, b3'
  }
]

is there any way to achieve this using underscoreJS ?

I can do this by for-loop. But In real scenario, its very large array containing JSON object of having 10 properties. So I need some performance oriented solution.

1 Answer 1

2

You can use array.reduce:

var datas = [{
    code: 1,
    name: 'a1'
  }, {
    code: 2,
    name: 'b1'
  }, {
    code: 1,
    name: 'a2'
  },
  {
    code: 1,
    name: 'a3'
  },
  {
    code: 2,
    name: 'b2'
  }
];

datas = datas.reduce((m, o) => {
  const found = m.find(e => e.code === o.code);
  found ? found.name += `, ${o.name}` : m.push(o);
  return m;
}, []);

console.log(datas);

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

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.