Im trying to filter an array of objects by comparing it to another array by looping through it's values. The problem is that the filter function stops at the first false by default, so if the loop returns (false, true, false) it will not pass the filter.
is there a way around this?
code (I've put simplfied arrays and objects in the code for the example):
const jobs = [
{id: 1,
location: 'AA'},
{id: 2,
location: 'BB'},
{id: 3,
location: 'CC'},
]
const filteredLocations = ['AA', 'CC']
const filteredJobs = jobs.filter(function(el, i) {
do {
return el.location === filteredLocations[i];
}
while (filteredLocations.length >= i)
})
// this only returns the first object instead of the desired first and third
Thank you!
Use the .filter function as it is intended, any return will be added to the returned array.
const jobs = [
{id: 1,
location: 'AA'},
{id: 2,
location: 'BB'},
{id: 3,
location: 'CC'},
]
const filteredLocations = ['AA', 'CC']
const filteredJobs = jobs.filter(el => {
return filteredLocations.includes(el.location);
});
sidenote, your code has 2 issues:
filteredLocations.length with the i (index) of the jobs array loop, jobs and filteredLocations are 2 different arrays, so that doesnt make sense to do soFilter doesn't stop at first false. It works correctly but it cannot return the first and third objects because the third object is on index 2 and you don't have any items in filteredLocations on that index.
I would advise you to replace the do-while loop with a simple finder function as follows:
const jobs = [
{id: 1,
location: 'AA'},
{id: 2,
location: 'BB'},
{id: 3,
location: 'CC'},
]
const filteredLocations = ['AA', 'CC']
const filteredJobs = jobs.filter(function(el, i) {
return filteredLocations.find((filteredLocation) => filteredLocation === el.location);
})
console.log(filteredJobs);