F
F
FastClick2022-01-04 19:34:31
JavaScript
FastClick, 2022-01-04 19:34:31

How to exclude repetitions in an array by a certain parameter?

There is an array:

[
  {
    "id": 1,
    "text": "Привет!"
  },
  {
    "id": 2,
    "text": "Как дела?"
  },
  {
    "id": 1,
    "text": "Привет!"
  },
  {
    "id": 3,
    "text": "Что делаешь?"
  },
  {
    "id": 2,
    "text": "Как дела?"
  },
  {
    "id": 1,
    "text": "Привет!"
  },
  {
    "id": 4,
    "text": "Как здоровье?"
  }
]


You need to somehow exclude repetitions by id to get the following view:

[
  {
    "id": 1,
    "text": "Привет!"
  },
  {
    "id": 2,
    "text": "Как дела?"
  },
  {
    "id": 3,
    "text": "Что делаешь?"
  },
  {
    "id": 4,
    "text": "Как здоровье?"
  }
]


In the Internet I found only solutions with simple arrays.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex, 2022-01-04
@FastClick

Use Array.prototype.filter() and Set. Inside the filter, check if your id is in a Set. If not, add to exclude all subsequent elements

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question