arrays - 如何在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 中具有更多属性的对象的索引
解决方案
你没有指定一种语言,所以我用 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
推荐阅读
- pandas - 在 Pandas 中使用 nans 创建箱线图时发出警告
- ansible - 当模板是有效的 json 时,Ansibles 'lookup' 返回不同的类型,我该如何防止呢?
- mysql - 为什么 update 子句需要很长时间,而 select 子句(具有相同的逻辑)不需要?
- c++ - C++ 矢量擦除功能无法正常工作
- excel - Dependednt 下拉列表和使用 INDIRECT 和 SUBSTITUTE 定义的不同名称变体
- javascript - 嵌套键值对分组到数组中
- gcc - 安装 gcc 成功,但无法启用
- node.js - Angular 通用设置 404 状态码不起作用
- c++ - c++ fstream::read 只返回第一个字符
- ruby-on-rails - Rails 中的 CRUD 模型,不使用资源和脚手架