-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}];
3
  • You are modifying result not the original array. Note that return in forEach does nothing Commented Jul 20, 2019 at 11:48
  • ahh that makes sense! Commented Jul 21, 2019 at 18:36
  • Does this answer your question? Merge duplicate objects in array of objects Commented May 9, 2022 at 20:30

3 Answers 3

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);

Sign up to request clarification or add additional context in comments.

Comments

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));

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.