Muzi Jack
Muzi Jack

Reputation: 798

Filtering Multiple items with ES6 array functions

This code only excludes John whats the best way of filtering out John, Brian and James?

const names = ["John", "Mary", "Max", "Brian", "James"]
const filterdNames = names.filter((value) => {
  return value !== 'John' && 'Brian' && 'James';
});
console.log(filterdNames)

Upvotes: 1

Views: 151

Answers (5)

Dan Gamble
Dan Gamble

Reputation: 4155

const names = ["John", "Mary", "Max", "Brian", "James"]
const filterdNames = names.filter((value) => {
  return ["John", "Brian", "James"].includes(value) === false;
});

You can use Array.includes

Upvotes: 3

Joey Gough
Joey Gough

Reputation: 3103

A string which is greater than or equal to one character long, will evaluate to true when coerced into a boolean. && is the logical AND operator. So in your filter you are stipulating that the name is not equal to John AND true AND true. You want to say, if the name is NOT John AND the name is NOT Brian AND the name is NOT James. It should look like this.

const names = ["John", "Mary", "Max", "Brian", "James"]
const filterdNames = names.filter((value) => {
  return value !== 'John' && value !== "Brian" && value !== "James"
});
console.log(filterdNames)

Upvotes: 0

Yashar Panahi
Yashar Panahi

Reputation: 3514

const names = ["John", "Mary", "Max", "Brian", "James"]
const filterdNames = names.filter((value) => {
  return value != "John" && value != 'Brian' && value != 'James';
});
console.log(filterdNames)

Upvotes: 1

Paul Fitzgerald
Paul Fitzgerald

Reputation: 12129

You are close, but your code is slightly wrong. You need to add value !== for each condition.

const names = ["John", "Mary", "Max", "Brian", "James"]
const filterdNames = names.filter((value) => {
  return value !== 'John' && value !==  'Brian' && value !==  'James';
});
console.log(filterdNames)

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370679

Create an array of the names you want to filter out beforehand, and then you can just test for the negation of an includes on it:

const names = ["John", "Mary", "Max", "Brian", "James"];
const filterOut = ['John', 'Brian', 'James'];
const filterdNames = names.filter(value => !filterOut.includes(value));
console.log(filterdNames)

Upvotes: 2

Related Questions