开发者问题收集

过滤数组(JS)

2018-05-04
598

我无法过滤包含对象的这个数组。如能给出解释,我将不胜感激。

说明:

// 使用 filter(),仅返回下面人员数组中的好友。 //将其分配给名为“trueFriends”的变量。

我的解决方案:

var trueFriends = [];

peopleIknow.filter(function(){
  for(var i = 0; i < peopleIknow.length; i++){
    if (peopleIknow[i].friend == true){
      trueFriends.push(peopleIknow[i]);
    }
  }
});

var peopleIknow = [
  { name: "Steve", friend: true },
  { name: "Dan", friend: false },
  { name: "Bart", friend: true },
  { name: "Sarah", friend: false },
  { name: "Michelle", friend: false },
  { name: "Holly", friend: true }
];
3个回答

您不应在 filter 中使用 for 循环。Filter 会遍历数组并根据条件返回所有元素

var peopleIknow = [
  { name: "Steve", friend: true },
  { name: "Dan", friend: false },
  { name: "Bart", friend: true },
  { name: "Sarah", friend: false },
  { name: "Michelle", friend: false },
  { name: "Holly", friend: true }
];

var o = peopleIknow.filter(e=> e.friend );

console.log(o)
Muhammad Usman
2018-05-04

filter 函数中使用 for 循环会违背目的 - 尝试仅使用 filter 函数进行迭代。您也不应该在声明数组之前尝试对数组进行 filter

filter 函数的第一个参数是被迭代的项目,并且您只对 friend 属性感兴趣,因此您只能提取 friend 属性。如果 friend 为真,则您希望将 true 返回给 filter 函数,以便将其包含在最终数组中 - 否则,返回 false 。因此,只需按原样返回 friend 属性即可。

const peopleIknow = [
  { name: "Steve", friend: true },
  { name: "Dan", friend: false },
  { name: "Bart", friend: true },
  { name: "Sarah", friend: false },
  { name: "Michelle", friend: false },
  { name: "Holly", friend: true }
];

const trueFriends = peopleIknow.filter(({ friend }) => friend);
console.log(trueFriends);
CertainPerformance
2018-05-04

不要在过滤器函数中运行 for 循环。过滤器非常易于使用。如果传递给过滤器的函数的结果为真,它会将该元素添加到返回值中。这就是您要找的!

var peopleIknow = [
  { name: "Steve", friend: true },
  { name: "Dan", friend: false },
  { name: "Bart", friend: true },
  { name: "Sarah", friend: false },
  { name: "Michelle", friend: false },
  { name: "Holly", friend: true }
];

var trueFriends = [];

//                                         only the friends where person.friend is truthy 
trueFriends = peopleIknow.filter(person => person.friend);

console.log(trueFriends);
Luca Kiebel
2018-05-04