user16041868
user16041868

Reputation:

compare and store string value by array in Javascript / node js

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

Upvotes: 1

Views: 476

Answers (4)

ikhvjs
ikhvjs

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

it-xp
it-xp

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

Rajdeep D
Rajdeep D

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

Torsten Barthel
Torsten Barthel

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

Related Questions