get all entriens from an array that do are neither in the category "cats" nor in "dogs" in javascript

index.tsx
const animals = ['lion', 'tiger', 'elephant', 'cat', 'dog', 'zebra'];
const excludedCategories = ['cats', 'dogs'];

const result = animals.filter(animal => {
  return !(excludedCategories.includes(animal));
});

console.log(result); // ['lion', 'tiger', 'elephant', 'zebra']
275 chars
9 lines

Explanation:

  • We create an array animals containing animals of different categories including 'cats' and 'dogs'.
  • We create an array excludedCategories containing the categories we don't want to include in our result.
  • We apply the filter method on the animals array with a callback function that does the filtering.
  • In the callback function, we use the includes method to check if the current animal is included in the excludedCategories array.
  • We negate the result using the logical NOT operator !, so we get the animals that are NOT in those categories.
  • The filter method returns a new array containing the filtered animals that do not belong in 'cats' or 'dogs'.
  • We log the result array to the console to confirm.

gistlibby LogSnag