0

I have an array Object which has same Id and different values. I need an output with same id and different values merged to the id.

Input:

let data = [{
    id: 1,
    value: 'Honda'
  },
  {
    id: 2,
    value: 'Fiat'
  },
  {
    id: 2,
    value: 'Porche'
  },
  {
    id: 1,
    value: 'Benz'
  }
];

Output:

result = [{
      id: 1,
      value: ['Honda', 'Benz']
    }, {
      id: 2,
      value: ['Fiat', 'Porche']
    }
adiga
  • 34,372
  • 9
  • 61
  • 83
  • 1
    Great...you have an objective. So where is the code showing how you have tried to solve this and outline of the problems you are having doing it? – charlietfl Jul 29 '19 at 11:42

3 Answers3

1

Hope it will helps you. But this question is duplicate

let data = [{
    id: 1,
    value: 'Honda'
  },
  {
    id: 2,
    value: 'Fiat'
  },
  {
    id: 2,
    value: 'Porche'
  },
  {
    id: 1,
    value: 'Benz'
  }
];

var output = [];

data.forEach(function(item) {
  var existing = output.filter(function(v, i) {
    return v.id == item.id;
  });
  if (existing.length) {
    var existingIndex = output.indexOf(existing[0]);
    output[existingIndex].value = output[existingIndex].value.concat(item.value);
  } else {
    if (typeof item.value == 'string')
      item.value = [item.value];
    output.push(item);
  }
});

console.dir(output);
1

const data = [{
    id: 1,
    value: 'Honda'
  },
  {
    id: 2,
    value: 'Fiat'
  },
  {
    id: 2,
    value: 'Porche'
  },
  {
    id: 1,
    value: 'Benz'
  }
];

const expectedResult = [{
      id: 1,
      value: ['Honda', 'Benz']
    }, {
      id: 2,
      value: ['Fiat', 'Porche']
    }
 ];
 
 const result = [];
 data.forEach((e, i) => {
    const indexOfExisting = result.findIndex(x => x.id === e.id);
    if (indexOfExisting === -1) {
      result.push({
          id: e.id,
          value: [e.value]
      })
    } else {
      result[indexOfExisting].value.push(e.value);
    }
 });
 
 // console.log(result)
 console.log(expectedResult)
Joey Gough
  • 2,753
  • 2
  • 21
  • 42
1

You can use Array.prototype.reduce() to achieve it.

let data = [{
    id: 1,
    value: 'Honda'
  },
  {
    id: 2,
    value: 'Fiat'
  },
  {
    id: 2,
    value: 'Porche'
  },
  {
    id: 1,
    value: 'Benz'
  }
];


let result = data.reduce((acc, ele) => {

  let filtered = acc.filter(el => el.id == ele.id)
  if (filtered.length > 0) {

    filtered[0]["value"].push(ele.value);

  } else {
    element = {};
    element["id"] = ele.id;
    element["value"] = []
    element["value"].push(ele.value);
    acc.push(element)

  }

  return acc;
}, [])
console.log(result)
Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46