Reputation:
I fetched data from database so its coming in string format and I want to check this string with my array data
fish.jpg
animal.jpg
fish.pdf
animal.pdf
mammal_bio.pdf
fish_bio.jpg
fruit_bio.pdf
I want to compare this data with my array which contain
["mammal_bio.pdf","fruit_bio.pdf","animal_bio.pdf","tree_bio.pdf"]
So i want to compare all the array values which contain _bio.pdf
and store them
matchedArray=["mammal_bio.pdf","fruit_bio.pdf"
unmatchedArray=["animal_bio.pdf","tree_bio.pdf"]
Upvotes: 1
Views: 476
Reputation: 5947
Don't use filter
but forEach or for loop instead because you don't need to loop through all items again to get the two arrays.
const input = `fish.jpg
animal.jpg
fish.pdf
animal.pdf
mammal_bio.pdf
animal_bio.pdf
fish_bio.jpg
tree_bio.pdf
fruit_bio.pdf`;
check = ["mammal_bio.pdf", "fruit_bio.pdf", "animal_bio.pdf", "tree_bio.pdf"];
const matched = [];
const unmatched = [];
input
.split("\n")
.forEach(item =>
check.slice(0, 2).includes(item)
? matched.push(item)
: check.slice(-2).includes(item)
? unmatched.push(item)
: null
);
console.log({ matched });
console.log({ unmatched });
Upvotes: 1
Reputation: 77
const input = `fish.jpg
animal.jpg
fish.pdf
animal.pdf
mammal_bio.pdf
animal_bio.pdf
fish_bio.jpg
tree_bio.pdf
fruit_bio.pdf`;
const inputList = input.split(/\n\s*/g)
const check = ["mammal_bio.pdf", "fruit_bio.pdf"];
const { matched, unmatched } = inputList.reduce((result, file) => {
if(/_bio\.pdf/.match(file)) {
if(check.indexOf(file) < 0) result.unmatched.push(file);
else result.matched.push(file)
}
return result
}, {
matched: [],
unmatched: []
})
Upvotes: 0
Reputation: 3910
First you can filter out the strings which endsWith
_bio.pdf
.
Then for matched
result filter with fiterArr and similarly for unmatched
result
let filterArr = ['mammal_bio.pdf','fruit_bio.pdf'];
let bioArr = arr.filter(a => a.endsWith('_bio.pdf'));
let matched = bioArr.filter(b => filterArr.includes(b));
let unmatched = bioArr.filter(b => !filterArr.includes(b));
Upvotes: 1
Reputation: 3458
Just use
Array.filter
method.
If you return true the item will be inside the new Array, false excludes the item.
const noBioList = []
const bioList = list.filter(item => {
if (item.includes('_bio.pdf') {
return true
} else {
noBioList.push(item)
return false
}
}
console.log(bioList)
console.log(noBioList)
Upvotes: 0