【问题标题】:How to find the index of a object with maximum properties in an array of objects in Javascript如何在Javascript中的对象数组中查找具有最大属性的对象的索引
【发布时间】:2018-11-02 19:42:16
【问题描述】:

如何在对象数组中查找具有最大属性的对象的索引。

假设我有一个下面的数组

    xyz = [
        {firstName: "John"}
        {firstName: "Jane", lastName: "Doe"}
        {firstName: "Mary", lastName: "Doe", age: "25", city: "newyork"}
        {firstname: "Jack", lastName: "sparrow", state: "NJ"}
    ]

我想得到 result = 2 的结果,其中 2 是数组 xyz 中具有更多属性的对象的索引

【问题讨论】:

    标签: arrays object indexof


    【解决方案1】:

    你没有指定一种语言,所以我用 ruby​​ 写了这个,因为即使你不熟悉它也很容易阅读。这个想法在所有语言中几乎都是一样的。

    def max_properties_index(xyz)
      max_count = 0
      result_index = nil
      xyz.each_with_index do |element, index|
        if element.keys.length > max_count
          max_count = element.keys.length
          result_index = index
        end
      end
      return result_index
    end
    
    xyz[max_properties_index(xyz)]  # returns the object in the array at the index
    

    【讨论】:

      猜你喜欢
      • 2014-05-07
      • 2013-05-06
      • 1970-01-01
      • 1970-01-01
      • 2022-07-08
      • 2018-07-09
      • 2014-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多