代码之家  ›  专栏  ›  技术社区  ›  AndrewL64

组合filter()和startsWith()以筛选数组

  •  1
  • AndrewL64  · 技术社区  · 8 年前

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

    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 回复  |  直到 8 年前
        1
  •  10
  •   Zohaib Ijaz    8 年前

    你可以做到

    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);
        2
  •  5
  •   brabster    8 年前

    抱歉,这并不是您所要求的,但是如果您对在一个操作中解决问题感兴趣,而不是使用 startsWith 具体来说,你可以用数字来做。。。

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

    由于没有字符串转换,它的效率可能会略高一些,并且不会出现其他字符串以相同方式开始匹配的问题。

        3
  •  2
  •   samanime    8 年前

    是的,您可以:

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

    然而,你可能不想这样做,因为在年份无效的情况下,你可能会遇到奇怪的事情(比如 19812 )。

    相反,您最好使用regex:

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

    这将只与20世纪80年代的年份相匹配。你也不必做额外的演员,所以它也有点干净。