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']
  }

]
7
  • Use array reduce ... note type: 'suv','van' is invalid, so please indicate what your requirements are including valid syntax Commented Oct 6, 2020 at 5:19
  • type will be array of string :- type: ['suv', 'van'] . I have to massage a data in such way Commented Oct 6, 2020 at 5:25
  • yes, use array reduce then Commented Oct 6, 2020 at 5:31
  • 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()] Commented Oct 6, 2020 at 5:50
  • 1
    @Ravi - it's ES6+ (i.e. ECMAScript 2015 and later) well, ``, ..., new Map and => is - otherwise, it's just javascript Commented Oct 6, 2020 at 6:51

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.