How to transform this items array to result array (objects should be with unique id and have key 'names' with array of name properties from objects with the same id):
Original array:
const items = [
{id: 1, name: 'a'},
{id: 2, name: 'b'},
{id: 3, name: 'c'},
{id: 1, name: 'd'},
{id: 3, name: 'f'}
];
Transformed array:
const result = [
{id: 1, names: ['a', 'd']},
{id: 2, names ['b']},
{id: 3, names: ['c', 'f']}
];
You can use Array.reduce to get the result.
const inputArray = [
{id: 1, name: 'a'},
{id: 2, name: 'b'},
{id: 3, name: 'c'},
{id: 1, name: 'd'},
{id: 3, name: 'f'}
];
const result = inputArray.reduce((acc, item) => {
const exist = acc.find(e => e.id == item.id);
// check exist in result
if (exist) {
// exist: push 'name' value to 'names' array
exist['names'].push(item.name);
} else {
// not exist: create new item in result
acc.push({
'id': item.id,
'names': [item.name]
});
}
return acc;
}, []);
console.log(result);