0

What I have

const pets = ['cat', 'dog', 'bat'];
console.log(pets.filter((pet) => !pet.includes('cat', 'dog')));

Expected output

["bat"]

Actual Output

["dog", "bat"]

This is just an example. In my real code, I'm doing a delete action to my global state (useContext, useReducer).

convocatorias: state.convocatorias.filter(
    (convocatoria) => !convocatoria._id.includes(action.payload)
),

action.payload is an array of ids.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Gabriel Cosi
  • 61
  • 1
  • 7

4 Answers4

2

Array.includes() takes one argument, you meant:

const pets = ['cat', 'dog', 'bat'];
console.log(pets.filter((pet) => !['cat', 'dog'].includes(pet)));
Always Helping
  • 14,316
  • 4
  • 13
  • 29
ekerner
  • 5,650
  • 1
  • 37
  • 31
1

You need to reverse your logic, like so:

pets.filter(pet => ['cat', 'dog'].includes(pet))
Isaac Corbrey
  • 553
  • 3
  • 20
1

includes determine whether an array includes certain value. In your case pet is not an array but it is the element which is currently under iteration.

Secondly includes with two parameters like includes('cat', 'dog') means search cat from array index 'dog'. Array index are number based so includes('cat', 'dog') will not make any sense

const excludedVals = ['cat', 'dog'];
const pets = ['cat', 'dog', 'bat'];
console.log(pets.filter((pet) => !excludedVals.includes(pet)));
brk
  • 48,835
  • 10
  • 56
  • 78
0

Includes() takes in one parameter but you have the alternative of using an && conditional or regex.

const pets = ['cat', 'dog', 'bat'];
console.log(pets.filter((pet) => !pet.includes('cat') && !pet.includes('dog')));

console.log(pets.filter((pet) => !(new RegExp(/(cat|dog)/).test(pet))))
Pavlos Karalis
  • 2,893
  • 1
  • 6
  • 14