Javascript 如何从.filter()函数中获取反向数据集?

Javascript 如何从.filter()函数中获取反向数据集?,javascript,node.js,Javascript,Node.js,考虑这个json对象: const animals = [ {name: "Bruno", type: "dog"}, {name: "Kira", type: "tiger"}, {name: "Max", type: "dog"}, {name: "Gogo", type: "parrot"}, {name: "Hixon", type: "dog"} ] 要获取所有狗,我们可以应用.filter(),如下所示: const dogs = animals.filter((anim

考虑这个json对象:

const animals = [
 {name: "Bruno", type: "dog"},
 {name: "Kira", type: "tiger"},
 {name: "Max", type: "dog"},
 {name: "Gogo", type: "parrot"},
 {name: "Hixon", type: "dog"}
]
要获取所有狗,我们可以应用.filter(),如下所示:

const dogs = animals.filter((animal) => {
 if (animal.type === "dog") {
  return animal;
 }
)

获取反向数据集的最佳实践是什么?在这种情况下,其他的动物类型呢

您没有按预期使用
过滤器
——它接收的回调将返回
true
false
,具体取决于项目是否应在集合中。JavaScript将对象分类为“truthy”项,因此您的代码仍然可以工作,但它应该看起来更像这样:

const dogs = animals.filter(animal => animal.type === "dog");
看看这个,它可能会更清楚,你是如何颠倒设置

const notDogs = animals.filter(animal => animal.type !== "dog");

您没有按预期使用
过滤器
——它接收的回调将返回
true
false
,具体取决于该项是否应在集合中。JavaScript将对象分类为“truthy”项,因此您的代码仍然可以工作,但它应该看起来更像这样:

const dogs = animals.filter(animal => animal.type === "dog");
看看这个,它可能会更清楚,你是如何颠倒设置

const notDogs = animals.filter(animal => animal.type !== "dog");