I have array like this, my id and name will be same for multiple objects but organizations values can be different
array= [
{id: 1, name: "Test1", organizations: 1},
{id: 1, name: "Test1", organizations: 2},
{id: 1, name: "Test1", organizations: 3},
{id: 2, name: "Test2", organizations: 4},
{id: 2, name: "Test2", organizations: 5},
{id: 2, name: "Test2", organizations: 6}
];
I want to convert this to be like this:
expectedArray = [
{id: 1, name: "Test1", organizations: [1,2,3]},
{id: 2, name: "Test2", organizations: [4,5,6]}
];
Can someone please help
const array= [
{id: 1, name: "Test1", organizations: 1},
{id: 1, name: "Test1", organizations: 2},
{id: 1, name: "Test1", organizations: 3},
{id: 2, name: "Test2", organizations: 4},
{id: 2, name: "Test2", organizations: 5},
{id: 2, name: "Test2", organizations: 6}
];
const mergeDuplicates= (field, uniqueField) => (source = [], value)=> {
const target = source.find( item => item[uniqueField] == value[uniqueField] );
if(target) target[field].push( value[field] );
else source.push({...value, [field]: [ value[field] ] });
return source;
}
const mergeOrganaizationsById = mergeDuplicates('organizations','id')
const result = array.reduce(mergeOrganaizationsById, [])
console.log(result)
You'll want to reduce.
array.reduce((acc, cur) => {
const i = acc.findIndex(a => a.id === cur.id && a.name === cur.name);
if (i === -1) return [...acc, {...cur, organizations: [cur.organizations]}];
return [...acc.slice(0, i), {...cur, organizations: [...acc[i].organizations, cur.organizations]}, ...acc.slice(i +1)];
}, []);
You can achieve the output using forEach by grouping based on name and then pushing the necessary fields into the output array.
const array = [
{ id: 1, name: "Test1", organizations: 1 },
{ id: 1, name: "Test1", organizations: 2 },
{ id: 1, name: "Test1", organizations: 3 },
{ id: 2, name: "Test2", organizations: 4 },
{ id: 2, name: "Test2", organizations: 5 },
{ id: 2, name: "Test2", organizations: 6 }
];
const current = Object.create(null);
const finalArr = [];
array.forEach(function (o) {
if (!current[o.name]) {
current[o.name] = [];
finalArr.push({ id: o.id, name: o.name, organizations: current[o.name] });
}
current[o.name].push(o.organizations);
});
console.log(finalArr);
.as-console-wrapper { max-height: 100% !important; top: 0; }