组合 filter() 和 startsWith() 来过滤数组

新手上路,请多包涵

假设我有一个数组常量,如下所示:

 const people = [
      { first: 'John', last: 'Doe', year: 1991, month: 6 },
      { first: 'Jane', last: 'Doe', year: 1990, month: 9 },
      { first: 'Jahn', last: 'Deo', year: 1986, month: 1 },
      { first: 'Jone', last: 'Deo', year: 1992, month: 11 },
      { first: 'Jhan', last: 'Doe', year: 1989, month: 4 },
      { first: 'Jeon', last: 'Doe', year: 1992, month: 2 },
      { first: 'Janh', last: 'Edo', year: 1984, month: 7 },
      { first: 'Jean', last: 'Edo', year: 1981, month: 8},
];

而我想返回一个每个80后的值。

我目前实现这一目标的工作职能是:

 const eighty = people.filter(person=> {
    if (person.year >= 1980 && person.year <= 1989) {
        return true;
    }
});


我的问题: 是否可以使用 startsWith()filter() 来替换:

 if (person.year >= 1980 && person.year <= 1989) {
    return true;
}

startsWith('198') 代替?

如果是,那么正确的方法是什么?

原文由 AndrewL64 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 476
2 个回答

你可以做

people.filter(person => String(person.year).startsWith('198'))

 const people = [
      { first: 'John', last: 'Doe', year: 1991, month: 6 },
      { first: 'Jane', last: 'Doe', year: 1990, month: 9 },
      { first: 'Jahn', last: 'Deo', year: 1986, month: 1 },
      { first: 'Jone', last: 'Deo', year: 1992, month: 11 },
      { first: 'Jhan', last: 'Doe', year: 1989, month: 4 },
      { first: 'Jeon', last: 'Doe', year: 1992, month: 2 },
      { first: 'Janh', last: 'Edo', year: 1984, month: 7 },
      { first: 'Jean', last: 'Edo', year: 1981, month: 8},
];

var filtered = people.filter(p => String(p.year).startsWith('198'));

console.log(filtered);

原文由 Zohaib Ijaz 发布,翻译遵循 CC BY-SA 3.0 许可协议

抱歉,这与您的要求不完全相同,但是如果您有兴趣在一次操作中解决问题而不是使用 startsWith 具体来说,您可以用数字来解决…

Math.floor(person.year / 10) === 198

由于没有字符串转换并且没有其他字符串以相同方式匹配的问题,因此它可能会更有效。

原文由 brabster 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏