I have a small application where I have an array of objects. Each object is a student and each student object has an array of tags that looks like this:
const students =
[ { name: "John", tags: [ 'tag1', 'tag2' ] }
, { name: "Leslie", tags: [ 'tag1' ] }
, { name: "Mark", tags: [ 'tag', 'tag2' ] }
]
Right now to search for students with the same tags I iterate through the array of objects and array of tags for each student which is O(n) squared.
const filterByTag = (filter) => {
let result = [];
initialStudents.map((student) => {
student.tags.map((tag) => {
if (tag.includes(filter)) {
result.push(student);
}
});
});
return result;
};
How can I reduce time complexity? I was thinking of creating an object with name->tags and then go through it, but it seems to be the same O(n) squared.
mapasforEach.