从map中的list的list中获取特定的索引



我不知道如何在javascript中做以下事情

在groovy中,如果我想遍历一个map,并且在该map中值是一个列表的列表,那么从列表的列表中获取一个特定的索引,即以下代码将工作

def total = value.collect { it.get(0) }*.toInteger().sum()

使用扩展运算符将所有检索到的数据转换为整数,然后使用sum

获得总数。如何在Javascript中做到这一点?

直接从JS-console:

[ ['1', 44], ['3', 55], ['42']].map( x => parseInt( x[ 0 ] ) ).reduce( ( res, x ) => res + x, 0 )
//or for an JS-Object/Map
Object.values( { a:'1', b:'3', c:'42' } ).map( x => parseInt( x ) ).reduce( ( res, x ) => res + x, 0 )
// or with plain JS Funtions
[ ['1', 44], ['3', 55], ['42']].map( function(x){ return parseInt( x[ 0 ] ) } ).reduce( function( res, x ){ return res + x }, 0 )

>> 46

这里的map是Groovy的collect的对应,而reduce取代了Groovy的inject。遗憾的是,JS中不存在sum快捷键…

最新更新