【问题标题】:Count occurrences of a string in an array using JavaScript [duplicate]使用JavaScript计算数组中字符串的出现次数[重复]
【发布时间】:2020-06-13 10:33:27
【问题描述】:

我有一个如下所示的数组:

[
  {pax_type: 'ADT', traveller_id: 1},
  {pax_type: 'ADT', traveller_id: 2},
  {pax_type: 'ADT', traveller_id: 3},
  {pax_type: 'CHD', traveller_id: 4},
  {pax_type: 'CHD', traveller_id: 5},
  {pax_type: 'INF', traveller_id: 6}
]

如何计算“ADT”在 JavaScript 中出现在这个数组中的次数?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您可以使用.filter():

    const input = [
      {pax_type: 'ADT', traveller_id: 1},
      {pax_type: 'ADT', traveller_id: 2},
      {pax_type: 'ADT', traveller_id: 3},
      {pax_type: 'CHD', traveller_id: 4},
      {pax_type: 'CHD', traveller_id: 5},
      {pax_type: 'INF', traveller_id: 6}
    ];
    
    const output = input.filter((e) => e.pax_type === 'ADT').length;
    console.log(output);

    【讨论】:

      【解决方案2】:

      你可以使用reduce作为

      var count = inputs.reduce((counter, {pax_type}) => pax_type == "ADT" ? counter + 1 : counter, 0);
      

      var inputs = [
        {pax_type: 'ADT', traveller_id: 1},
        {pax_type: 'ADT', traveller_id: 2},
        {pax_type: 'ADT', traveller_id: 3},
        {pax_type: 'CHD', traveller_id: 4},
        {pax_type: 'CHD', traveller_id: 5},
        {pax_type: 'INF', traveller_id: 6}
      ]
      
      var count = inputs.reduce((counter, {pax_type}) => pax_type == "ADT" ? counter + 1 : counter, 0);
      console.log(count)

      【讨论】:

        猜你喜欢
        • 2012-08-11
        • 1970-01-01
        • 2019-07-31
        • 2012-05-31
        • 2011-03-02
        • 2017-12-22
        • 2013-11-04
        相关资源
        最近更新 更多