0

I have two Arrays in a VueJS instance. The arrays display courses a student can attend at school. First are the courses the user attend, and second are all the courses with students in them.

The arrays looks like this:

let mainVue = new Vue({
    el: '#mainContent',
    data: {
      myCourses: [{Course: "A"}, {Course: "B"}],
      allCourses: [{Course: "A"}, {Course: "B"}, {Course: "C"}, {Course: "A"}]
}

Both arrays consist of data populated from user inputs, so they changes over time. The first array are user specific content (Courses the user attends) and the second array are an array of all courses which have someone attend to.

I want to check the amount of people who attend the same course as the user. So in this case I want to check how many from array myCourses (Course a and b) are in array allCourses.

In other words, I want to check how many occurrences from array "myCourse" are in the array "allCourses".

2 Answers 2

1

May be a computed prop would suite you (check id/course names intersection)

const mainVue = new Vue({
    el: '#mainContent',
    
    data: {
      myCourses: [{Course: "A"}, {Course: "B"}],
      allCourses: [{Course: "A"}, {Course: "B"}, {Course: "C"}, {Course: "A"}],
   },
   
   computed: {
      allCoursesCounts() {
        return this.allCourses.reduce((acc, { Course }) => {
          acc[Course] = (acc[Course] || 0) + 1
          return acc
        }, {})
      },
      subscribedTo() {
        const allCoursesCounts = this.allCoursesCounts

        return this.myCourses.map(({ Course }) => ({
          courseName: Course,
          amountOfUsers: allCoursesCounts[Course] || 0,
        }))
      }
   }
});
<div id="mainContent">
    <div v-for="({ courseName, amountOfUsers }) of subscribedTo" :key='courseName'>
      <span>Course {{ courseName }} - {{ amountOfUsers }}</span>
    </div>
</div>
Sign up to request clarification or add additional context in comments.

7 Comments

I don't think you can use an includes here because it measures on shallow equality
@KevinIzuchukwu that's why I suggested to compare something like array item IDs. It could be changed to a function that performs deep comparison, I usually use lodash
This kinda works. But the result is 4 and I want to filter the result to be like "Course A: 2" Course B: 2". So you can see the total attendences on each course and not the total amount of all courses.
@egx I changed the code according to your requirement. (Didn't get what you need at first, sorry :) )
Thank you man! This look perfect. I've marked your answer as solved :-)
|
0

You want to filter all courses that have an occurrence in myCourses

allCourses.filter(course => {
   return myCourses.find(m => {
      return m.Course === course.Course
   })
}).length

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.