簡體   English   中英

合並filter()和startsWith()以過濾數組

[英]Combine filter() and startsWith() to filter array

假設我有一個數組常量,如下所示:

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

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

你可以做

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

抱歉,這不是您所要的,但是如果您有興趣通過一個操作而不是使用startsWith來解決問題,則可以通過數字方式進行操作...

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

由於沒有字符串轉換,並且沒有其他字符串以相同的方式啟動匹配的問題,因此它可能會更加高效。

是的你可以:

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

但是,您可能不想這樣做,因為您可能會遇到年份無效的怪異事物(例如19812 )。

相反,使用regex會更好:

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

這將僅與1980年代匹配。 您也不必進行額外的轉換,因此它也更清潔一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM