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

时间:2018-04-25 19:54:02

标签: javascript ecmascript-6

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

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') 代替?

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

3 个答案:

答案 0 :(得分:5)

你可以做到

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);

答案 1 :(得分:5)

这不是你提出的问题,对不起,如果你有兴趣在一次操作中解决问题而不是专门使用startsWith,你可以用数字来做...

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

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

答案 2 :(得分:2)

是的,你可以:

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

然而,你可能不想这样做,因为你可能遇到年度无效的奇怪事情(如果它是19812)。

相反,你最好使用正则表达式:

people.filter(person => /^198\d$/.test(person.year));

这只会与20世纪80年代的年份相匹配。你也不需要做额外的演员,所以它也有点清洁。

相关问题