使用ES6数组函数过滤多个项目

时间:2018-10-25 08:26:52

标签: javascript arrays

此代码仅排除 John 是什么过滤出 John Brian James 的最佳方法?< / p>

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

5 个答案:

答案 0 :(得分:3)

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

您可以使用Array.includes

答案 1 :(得分:2)

创建一个要预先过滤掉的名称的数组,然后就可以测试其上的includes是否取反:

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

答案 2 :(得分:2)

您很亲密,但是您的代码略有错误。您需要为每个条件添加value !==

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

答案 3 :(得分:1)

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

答案 4 :(得分:0)

一个大于或等于一个字符长的字符串,被强制转换为布尔值时将评估为true。 &&是逻辑AND运算符。因此,在您的过滤器中,您规定名称不等于John AND true AND true。您想说的是,如果名字不是John,名字不是Brian,名字不是James。它应该看起来像这样。

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