Estoy haciendo un curso de javascript y estoy tratando de crear una función que filtre de la matriz y elimine un valor dado de ella. NOTA: tengo que usar el método filter().
Lo he intentado de varias maneras pero sin éxito. ¿Qué estoy haciendo mal?
Aquí el código:
function Student(id, name, subjects = []) { this.id = id; this.name = name; this.subjects = subjects; } Student.prototype.addSubject = function(subject) { this.subjects = [...this.subjects, subject]; } Student.prototype.removeSubject = function(remove) { this.subjects.filter(function(remove) { return this.subjects !== remove }) } const student1 = new Student(1, 'Reed'); student1.addSubject('Math'); console.log(student1.subjects); student1.removeSubject('Math'); console.log(student1.subjects)
Aprecia tu tiempo
filter
no modifica la matriz, devuelve una nueva. this.subjects = this.subjects.filter
más un cambio en la forma de filtrar:
function Student(id, name, subjects = []) { this.id = id; this.name = name; this.subjects = subjects; } Student.prototype.addSubject = function(subject) { this.subjects = [...this.subjects, subject]; } Student.prototype.removeSubject = function(remove) { this.subjects = this.subjects.filter(function(current) { return current !== remove }) } const student1 = new Student(123,'pepe') student1.addSubject('a'); student1.addSubject('Math'); student1.addSubject('b'); student1.addSubject('c'); console.log(student1.subjects); student1.removeSubject('Math'); console.log(student1.subjects)
Puede usar .push()
y .splice()
para modificar la matriz de subjects
en el lugar, en lugar de volver a crearla para cada modificación, lo que a) es un desperdicio yb) puede causar errores difíciles de encontrar.
Pero absolutamente debe crear una nueva matriz en el punto de creación del objeto, para evitar modificar inadvertidamente el parámetro de los subjects
fuera durante la vida útil de la instancia del Student
.
function Student(id, name, subjects = []) { this.id = id; this.name = name; if (!Array.isArray(subjects)) throw new Error("subjects must be an array"); this.subjects = [...subjects]; } Student.prototype.addSubject = function (subject) { this.subjects.push(subject); } Student.prototype.removeSubject = function (subject) { const pos = this.subjects.indexOf(subject); if (pos > -1) this.subjects.splice(pos, 1); } const student1 = new Student(1, 'Reed'); student1.addSubject('Math'); console.log(student1.subjects); student1.removeSubject('Math'); console.log(student1.subjects)