首页 > 解决方案 > 如何在Javascript中的对象数组中查找具有最大属性的对象的索引

问题描述

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

假设我有一个下面的数组

    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 中具有更多属性的对象的索引

标签: arraysobjectindexof

解决方案


你没有指定一种语言,所以我用 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

推荐阅读