0

How to skip found values in else condition, now in my code it outputs duplicates.

 this.comparedGenesList = this.genesList.map((item) => {
      const foundedItem = this.data.probes.find(({name}) => name.toUpperCase() === item.toUpperCase());
        if (foundedItem !== undefined) {
         return {name: foundedItem.name.trim(), matched: true, id: foundedItem.id};
        } else {
          return {name: item.trim(), matched: false, id: undefined};
        }
    });
Palle Due
  • 5,929
  • 4
  • 17
  • 32
  • You looking for `.filter()`? – mousetail Jul 09 '21 at 07:12
  • i tried but how can filter in my situation? (in map) – Aw KingOftheworld Jul 09 '21 at 07:14
  • 2
    `.map()` is a transform method; if you give it an array of length N, it will output an array of length N. Skipping duplicates shouldn't enter in its logic. _After_ the `.map()`, what you should do is chain a `.filter()` to [remove the duplicates](https://stackoverflow.com/questions/2218999/how-to-remove-all-duplicates-from-an-array-of-objects). – Jeremy Thille Jul 09 '21 at 07:15

2 Answers2

2

Just tack an array.filter on the end to remove all duplicates.

.filter((item, index, array) =>  
  index === array.findIndex((t) => (
    t.name === item.name && t.id === item.id
  ))
)

which basically says

For each item in the array, perform a test to see if we need to filter it out. The test is: find the first matching object with the same name and id as the one we're testing. If the index of that found object is the same as the index of the one we're testing, let it through. If it's a different index (as in, we found a duplicate later on) discard it.

Here is a testable snippet:

this.genesList = ['fred','john','dave','john','dave']
this.data = {probes:[{name:'john', id:2}]}

this.comparedGenesList = this.genesList.map((item) => {
  const foundedItem = this.data.probes.find(({name}) => name.toUpperCase() === item.toUpperCase());
  if (foundedItem !== undefined) {
    return {
      name: foundedItem.name.trim(),
      matched: true,
      id: foundedItem.id
    };
  } else {
    return {
      name: item.trim(),
      matched: false,
      id: undefined
    };
  }
}).filter((item, index, array) =>
  index === array.findIndex((t) => (
    t.name === item.name && t.id === item.id
  ))
)

console.log(this.comparedGenesList )
Kinglish
  • 23,358
  • 3
  • 22
  • 43
0

You can use filter() rather than map().

this.comparedGenesList = this.genesList.filter((item) => {
  const isItemFounded = this.data.probes.some((name) => name.toUpperCase() === item.toUpperCase());
  return !isItemFounded;
})
.map((item) => {
      return {name: item.name.trim(), matched: true, id: item.id};
});
Drashti Dobariya
  • 2,455
  • 2
  • 10
  • 23