1

How to join .map and .filter to filter and remove duplicate in object array?

I currently have to use two variables for this:

Image example

See code Sandbox example

const arrayOne = [
    {
      id: 1,
      name: "João",
      city: {
        id: 1,
        name: "Rio de Janeiro"
      }
    },
    {
      id: 1,
      name: "Pedro",
      city: {
        id: 2,
        name: "Salvador"
      }
    },
    {
      id: 1,
      name: "Tiago",
      city: {
        id: 1,
        name: "Rio de Janeiro"
      }
    }
  ];

  const arrayTwo = arrayOne.map(function (item, index) {
    return item.city;
  });

  const arrayThree = arrayTwo.filter(
    (elem, index, arr) => index === arr.findIndex((t) => t.id === elem.id)
  );

2 Answers 2

5

If your filter is just to remove duplicates consider creating a Map which simply overwrites all duplicate city.ids. This can then be converted back to an array, here using spread syntax on the Map.values().

const arrayOne = [
  { id: 1, name: 'João', city: { id: 1, name: 'Rio de Janeiro' } },
  { id: 1, name: 'Pedro', city: { id: 2, name: 'Salvador' } },
  { id: 1, name: 'Tiago', city: { id: 1, name: 'Rio de Janeiro' } },
];

const arrayTwo = [...new Map(arrayOne.map(({ city }) => [city.id, city])).values()];

console.log(arrayTwo);

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

1 Comment

Thank you for your help!
4

Just chain them together?

  const result = arrayOne.map(function (item, index) {
    return item.city;
  }).filter(
    (elem, index, arr) => index === arr.findIndex((t) => t.id === elem.id)
  );

If you mean that you want to map and filter at the same time, then you can use either flatMap or reduce as described in another Q/A: https://stackoverflow.com/a/34398349/211627

1 Comment

Thank you for your help!

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.