【问题标题】:Getting index of first object in an array that has "name" property starting with selected letter获取数组中第一个对象的索引,该数组具有以选定字母开头的“名称”属性
【发布时间】:2016-11-27 20:56:05
【问题描述】:

我有一个按字母顺序排列的国家/地区列表,如下所示:

[
  {
    name: "United States",
    country_code: "US",
    dial_code: "+1"
  },
  { .. etc }
]

我正在监听用户的按键输入,假设他们按下“a”键。我想获取名称以“a”开头的数组中第一个对象的索引。

现在我的问题不是如何执行整个操作,而是关于如何在数组中找到此类索引的建议/想法,如果我已经知道用户按下了“a”。我正在研究 lodash 来解决这个问题,但无法弄清楚,因此如果它们适合解决这个问题,请随意使用第三方库。

【问题讨论】:

    标签: javascript arrays json object lodash


    【解决方案1】:

    使用_.findIndex 查找第一个匹配项索引:

    var firstIndex = _.findIndex(countries, function(country) {
        return _.chain(country)
            .get('name', '')
            .lowerCase()
            .startsWith('a')
            .value();
    });
    

    【讨论】:

      【解决方案2】:

      您可以使用带有第一个字母和索引的对象来访问给定的数组和具有相同字母的数组末尾,例如

      var abc = {
          u: [0, 1]
      }
      

      以字母'u'为例:

      var countries = [{ name: "United Kingdom", country_code: "UK", dial_code: "+44" }, { name: "United States", country_code: "US", dial_code: "+1" }, { name: "France", country_code: "FR", dial_code: "+33" }, { name: "Italy", country_code: "IT", dial_code: "+16" }],
          abc = Object.create(null);
      
      countries.sort(function (a, b) {
          return a.name.localeCompare(b.name);
      });
      
      countries.forEach(function (a, i) {
          var c = a.name[0].toLowerCase();
          if (!abc[c]) {
              abc[c] = [i];
          }
          abc[c][1] = i + 1;
      });
      
      console.log(Array.prototype.slice.apply(countries, abc['u']));
      console.log(abc);
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      【讨论】:

        【解决方案3】:

        你可以实现一个函数来过滤名称以作为参数的字母开头的国家:

        var countries = [
          {
            name: "United States",
            country_code: "US",
            dial_code: "+1"
          },
          {   name: "France",
            country_code: "FR",
            dial_code: "+33"
          },
          {   name: "Italy",
            country_code: "IT",
            dial_code: "+16"
          }
        ]
        var selectedCountries = (array, letter) => array.filter(x => x.name.indexOf(letter) === 0);
        
        console.log(selectedCountries(countries, "F"));

        【讨论】:

          【解决方案4】:

          如果旧版浏览器不是问题,您可以结合使用Array.findString.startsWith

          var obj = arr.find( x => x.name.startsWith('a'));
          

          【讨论】:

            猜你喜欢
            • 2021-11-03
            • 1970-01-01
            • 1970-01-01
            • 2021-07-24
            • 2022-10-19
            • 2021-08-30
            • 2018-03-15
            • 2011-08-14
            相关资源
            最近更新 更多