Nancy
Nancy

Reputation: 1051

Unsure what this code is doing? I want it to do the opposite of what it's actually doing

I'm working on this project that someone else already started and I'm unsure how this part of code works, it's actually doing what I don't want it to do.

Currently when I use a select multiple and press the button it adds to the array the ones that I DIDN'T select, when I want it to add the ones I did select to the array, this array is then used as the data for a table so it's obvious it's selecting the wrong stuff.

This is the method when the button is pressed. package_courses is the final array that the table data is populated with.

addCourses() {
    const currentCourses = this.packageForm.package_courses.map((item) => item.course_id);
    const courses = this.courses.filter((item) => {
        return this.selectedCourses.indexOf(item.id) && currentCourses.indexOf(item.id) < 0
    });

    courses.forEach((course) => {
        this.packageForm.package_courses.push({
            course_id: course.id,
            course: course,
            price: 0
        });
    });
    this.selectedCourses = [];
},

Upvotes: 0

Views: 41

Answers (1)

User2585
User2585

Reputation: 372

In the second line the filter method loops all items in this.courses and returns only those items where the statement inside returns true. indexOf is an array method that searches an array for the specified item and returns the position of the item in the array or -1 if the items isn't found. so I guess what you want to do is filter for courses where indexOf is greater or equals than/to 0, instead of less, here is your code modified.

addCourses() {
    const currentCourses = this.packageForm.package_courses.map((item) => item.course_id);
    const courses = this.courses.filter((item) => {
        return this.selectedCourses.indexOf(item.id) && currentCourses.indexOf(item.id) >= 0
    });

    courses.forEach((course) => {
        this.packageForm.package_courses.push({
            course_id: course.id,
            course: course,
            price: 0
        });
    });
    this.selectedCourses = [];
},

Upvotes: 1

Related Questions