0

Suppose we have an array of objects like :

[ { LeadId: AABB , Phone: 1234 , } ,

{ LeadId: ABCD , Phone: 5678 , } ,

{ LeadId: EERR , Phone: 1234 , } ,

{ LeadId: FFGG , Phone: 5678 , } ]

And an array of phone numbers :

[   1234 , 5678 , 6565  ]

I want to remove the first occurrence of every phone number in the first list , hence the result would be :

{ LeadId: EERR , Phone: 1234 , } ,

{ LeadId: FFGG , Phone: 5678 , }

Assume that leadsToInsert is the array that we need to remove occurrences from and phoneNumbers is the array of phone numbers

I've tried with Underscore :

        const leftOvers = _.without(
          leadsToInsert,
          _.find(leadsToInsert, {
            Phone: phoneNumbers
          })
        );

When I run this piece of code all the objects in leadsToInsert remains and nothing is filtered.

When did I go wrong ?

JAN
  • 21,236
  • 66
  • 181
  • 318

2 Answers2

1

You could take an object and set the hash table to true for next filtering.

var data = [{ LeadId: 'AABB', Phone: 1234 }, { LeadId: 'ABCD', Phone: 5678 }, { LeadId: 'EERR', Phone: 1234 }, { LeadId: 'FFGG', Phone: 5678 }],
    omitFirst = [1234, 5678, 6565],
    result = data.filter(
        (seen => ({ Phone }) => !omitFirst.includes(Phone) || seen[Phone] || !(seen[Phone] = true))
        ({})
    );

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Convert the phones array to a Set, and the use Array.filter(), and delete the current phone from the Set. The Set.delete() method returns true if the item was removed successfully, and false otherwise. So for the first item !phones.delete() is false (removing the item from the array), while the other items with the same phone would be preserved.

const data = [{ LeadId: 'AABB', Phone: 1234 }, { LeadId: 'ABCD', Phone: 5678 }, { LeadId: 'EERR', Phone: 1234 }, { LeadId: 'FFGG', Phone: 5678 }]
const phones = [1234, 5678, 6565]

const phonesSet = new Set(phones)

const result = data.filter(({ Phone }) => !phonesSet.delete(Phone))

console.log(result)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209