Richard C
Richard C

Reputation: 171

Filter array with includes failing

This behaves as expected and I get back "banana"...

let like = ["banana"];
let fruits = [
    { name: "apple" },
    { name: "banana" },
    { name: "pear" },
];

let fruits2 = fruits.filter((f: any) => like.includes(f.name));
console.log(fruits2);

But this fails...

ticketDetailsSubset2 = ticketDetailsArray.filter(
 (i: any) => !excludeTickets.includes(i["stl19:TicketNumber"][0])            
);

The array for excludeTickets is simply this...

0: ["0017522827238"]

I am looping through the ticketDetailsArray which includes 3 objects ...

I should get back only the 3rd object as the 1st two objects are in the excludeTickets. Even though I'm a beginner I threw in the fruit example to prove that I am on the right track. I also manually tried doing

!excludeTickets.includes("0017522827238") 

and it still didn't work. Everything is returned. I have a similar .filter piece of code with another conditional check and it works. What's the difference - the .includes ?? so I'm guessing includes is not meant to do what I think it does but then again the fruit option works??

Upvotes: 0

Views: 44

Answers (1)

Barmar
Barmar

Reputation: 780949

excludeTickets is a 2-dimensional array (notice the square brackets around excludeTickets[0]), not an array of strings. You need to flatten it.

flatTickets = excludeTickets.flatMap(el => el);
ticketDetailsSubset2 = ticketDetailsArray.filter(
    (i: any) => !flatTickets.includes(i["stl19:TicketNumber"][0])            
);

Upvotes: 1

Related Questions