Home > other >  Compare two arrays of objects and filter out similar property values?
Compare two arrays of objects and filter out similar property values?

Time:04-06

I'm calling two API endpoints: the first one will return an array of clients whose account is currently active with us, and the second will return an array of ALL clients (current and past) regardless of their current status.

I'm creating a dropdown menu that will basically add a client to the "active client" array. To create this dropdown, I need to filter out all clients from the "All clients array" that already exist in the "Active clients array".

Eg:

ALL clients

[{name: "Martha", id: 1}, {name: "John", id: 2},{name: "Jane", id: 3}, {name: "Mary", id: 4}]

Active clients

[{name: "John", customerid: 2}, {name: "Mary", customerid: 4}]

(Yes, the backend dev did give them different property names)

My new array should obviously be:

[{name: "Martha", id: 1}, {name: "Jane", id: 3}]

I can iterate through this list to populate the dropdown menu and only submit a client to the backend that doesn't already have an active account with us.

CodePudding user response:

If you can consider the ids to be unique then you could do something like this:

function removeDuplicates(allClients, activeClients) {
  const activeClientIds = new Set(
    activeClients.map((client) => client.customerid)
  );

  return allClients.filter((client) => !activeClientIds.has(client.id));
}

const allClientsArr = [
  { name: "Martha", id: 1 },
  { name: "John", id: 2 },
  { name: "Jane", id: 3 },
  { name: "Mary", id: 4 },
];
const activeClientsArr = [
  { name: "John", customerid: 2 },
  { name: "Mary", customerid: 4 },
];

const result = removeDuplicates(allClientsArr, activeClientsArr);

console.log(result);

CodePudding user response:

You can use a simple .filter. Also, your example result is actually missing a element.

const all = [{name: "Martha", id: 1}, {name: "John", id: 2},{name: "Jane", id: 3}, {name: "Mary", id: 4}]
const old = [{name: "John", customerid: 2}, {name: "Mary", customerid: 4}];
const oldIds = old.map(customer => customer.customerid);
console.log(all.filter(customer => !(customer.id in oldIds)))

  • Related