Reputation: 15
So I have an array which looks like the one displayed below:
const newTeachers = [
{ firstName: "Steve", subjects: ["English", "Maths", "History"] },
{ firstName: "Celia", subjects: ["Maths", "Science"] },
];
I want to create a function which takes in 2 parameters 1 being the array and 2nd being the filter string value.
function fliterSubject(teachers, subject) {
}
I have looked into the inbuilt way which is to implement this line of code:
return newCandidates.filter(teacher=> teacher.subjects.includes(subject));
However I want to understand how I can filter it manually instead of using the inbuilt filter function.
Upvotes: 1
Views: 2150
Reputation: 37755
Explanation
You can achieve this with a simple for loop.
So you need to loop the array you're getting as argument in function.
Create a temporary array and push the values into it only if certain condition matches and return that array from function.
So something like this :-
function manuamMap(input, search){
Let temp = [];
for(let i=0; i<limit; i++) {
if(some confition){
temp.push();
}
}
return temp
}
Upvotes: 2
Reputation: 2299
Please check this.
var filterSubject = function(teachers, subject) {
var filteredTeachers = [];
for (var i=0; i<=teachers.length-1; i++) {
var teacher = teachers[i];
for (var j=0; j<=teacher.subjects.length-1; j++) {
if (teacher.subjects[j].toLowerCase()== subject.toLowerCase()) {
filteredTeachers.push(teacher);
}
}
}
return filteredTeachers;
}
Please check an example @ CodePen https://codepen.io/animatedcreativity/pen/213ddd0a66b73b05c907da72c8aef3e3
Upvotes: 2