-1

i have a problem, with my code basically i'm trying to merge the duplicate objects and add the additional property 'admin' set to 'true' and for unique objects additional property 'admin' set to 'false'

const addresses = [{name: 'Paul', id: 2}, {name: 'John', id: 1}, {name: 'John', id: 1}];

//combine duplicate object and add property admin: true

let result = [];
addresses.forEach(elem => {
  let match = result.find(r => r.id === elem.id);
  if(match) {
    return {...match, ...elem, admin: true};
  } else {
    result.push({...elem, admin: false });
  }
});

but im doing this incorrectly as the output i get is

const addresses = [{name: 'Paul', id: 2}, {name: 'John', id: 1}, {name: 'John', id: 1}];
Ali Khalil
  • 126
  • 1
  • 11

3 Answers3

2

Using reduce()

const addresses = [{name: 'Paul', id: 2}, {name: 'John', id: 1}, {name: 'John', id: 1}];

const result = addresses.reduce((a, o) => ({...a, ...{
  [o.id]: { ...o, admin: !a[o.id] }
}}), {});

console.log(Object.values(result));
User863
  • 19,346
  • 2
  • 17
  • 41
2

You can use reduce to create a unique array that sets admin property to true for duplicate addresses as follows:

const addresses = [{name: 'Paul', id: 2}, {name: 'John', id: 1}, {name: 'John', id: 1}];

const result = addresses.reduce((acc, address) => {
  const dup = acc.find(addr => addr.id === address.id);
  if (dup) {
    dup.admin = true;
    return acc;
  }
  address.admin = false;
  return acc.concat(address);
}, [])

console.log(result);
antonku
  • 7,377
  • 2
  • 15
  • 21
0

You can use array#reduce to group the unique addresses and then check for admin property in the object and accordingly assign the value.

const addresses = [{name: 'Paul', id: 2}, {name: 'John', id: 1}, {name: 'John', id: 1}],
      users = Object.values(addresses.reduce((r,o) => {
        r[o.id] = {...o, admin: !r[o.id]};
        return r;
      }, {}));
console.log(users);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51