D
D
Danoneko2022-04-20 17:22:11
JavaScript
Danoneko, 2022-04-20 17:22:11

How to find objects and add them to arrays of objects without duplication?

There is an array of objects (tasks):

[
{
   "id": "0", 
   "id_cource": "2", 
   "name": "Задача", 
   "teacher": [
      {"id": "6"}],
   "student": [
      {"id":"2"},
      {"id": "0"}
   ],
},
{
   "id": "1", 
   "id_cource": "2", 
   "name": "Задача", 
   "teacher": [
      {"id": "6"},
      {"id": "4"},
      {"id": "0"}],
   "student": [
      {"id":"0"}
   ],
},
...etc
]

I did a search on all objects (tasks) in this array that belong to a particular course by id_cource . That is, the first two tasks belong to the course with id=2 . Let's say this variable tasksCourse and in our example it will look like this - (2) [{...}, {...}].

Now, from the selected tasks that are stored in the tasksCourse variable , you need to take the values ​​of the teacher key and write them into one array of objects without duplicates. That is, it is conditional that the constant const teacherTaskCource = [];contains (3) [ {"id": "6"},{"id": "4"},{"id": "0"}].

And the same array of students const studentTaskCource = [];which is (2) [ {"id": "2"},{"id": "0"}].

Code like this
tasksCourse.filter((i) =>  teacherTaskCource.push(i.teachers))

Leading to the fact that I get an array of arrays with objects (2) [Array(1), Array(2)].

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
wonderingpeanut, 2022-04-20
@wonderingpeanut

Well, like this

// объект который будет хранить айдишники учителей
const freq = {}
// финальный массив
const res = [];
for (const el of tasks.teacher) {
  // для каждого учителя смотрим, уникальный ли он
  // если учитель есть в объекте freq, значит не уникальный, едем дальше
  if (el.id in freq) continue;
  // в противном случае записываем айди учителя в объект и пушим объект учителя в результирующий массив
  freq[el.id] = 1;
  res.push(el);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question