0

Sample Question : - Given Array : -

var arr = [
  {
    name: 'honda',
    color: 'red',
    type : 'car'
  }, 
  {
    name: 'honda',
    color: 'red',
    type : 'suv'
  },
  {
    name: 'honda',
    color: 'green',
    type: 'van'
  },
  {
    name: 'toyota',
    color: 'red',
    type: 'suv'
  },
   {
    name: 'toyota',
    color: 'red',
    type: 'van'
  }

]

Duplicate object depends on two fields : -

  1. name
  2. color

and if "type" is different and "name", "color" are same then "type" will be concatenated like array of string as shown in expected answer.

Expected Answer :

[
  {
    name: 'honda',
    color: 'red',
    type : ['car','suv']
  }, 
 
  {
    name: 'honda',
    color: 'green',
    type: ['van']
  },
  {
    name: 'toyota',
    color: 'red',
    type: ['suv','van']
  }

]
Sharry
  • 1
  • 1
  • Use array reduce ... note `type: 'suv','van'` is invalid, so please indicate what your requirements are including valid syntax – Jaromanda X Oct 06 '20 at 05:19
  • type will be array of string :- type: ['suv', 'van'] . I have to massage a data in such way – Sharry Oct 06 '20 at 05:25
  • yes, use array reduce then – Jaromanda X Oct 06 '20 at 05:31
  • Thanks I can remove the duplicates but adding how to add "type" field as an array if obj is similar – Sharry Oct 06 '20 at 05:42
  • 1
    `result = [...arr.reduce((a,{name,color,type})=>(a.set(\`${name}:${color}\`,(a.get(\`${name}:${color}\`)||{name, color, type:[]})),a.get(\`${name}:${color}\`).type.push(type),a),new Map).values()]` – Jaromanda X Oct 06 '20 at 05:50
  • @JaromandaX what is this technique. can you tell me? or can you give me reference for more of it. i want to learn it. – Ravi Oct 06 '20 at 06:15
  • 1
    @Ravi - it's ES6+ (i.e. ECMAScript 2015 and later) well, `\`\``, `...`, `new Map` and `=>` is - otherwise, it's just javascript – Jaromanda X Oct 06 '20 at 06:51

0 Answers0