我想检索满足特定条件的数组中元素的所有索引。例如,如果我有一个像这样的数组:
var countries = ["India", "Australia", "United States", "Brazil"];
我想得到那些字符串长度大于 5 的元素的索引,我应该得到一个像这样的数组
[2, 3]
甚至是像这样的对象:
{
2: "United States",
3: "Australia"
}
我可以利用 JavaScript 或 underscore.js 中的任何内置/ native 函数吗?
最佳答案
在 vanilla JS 中,获取索引:
var longnames = ["India", "Australia", "United States", "Brazil"]
.map( function( item, idx ){
// convert the names to indexes if name is linger than 5 characters
return ( item.length > 5) ? idx : null
}).filter(function(item){
// fiter out the nulls
return item;
});
// returns [1,2,3] since "Australia".length > 5
由于下划线同时具有 .map
和 .reduce
方法,因此您应该能够“下划线化”该解决方案;)
以 { index : name }
形式创建对象:
var longnames = ["India", "Australia", "United States", "Brazil"]
.reduce( function( ret, name, idx ){
if( name.length > 5 ){
ret[ idx ] = name;
}
return ret;
}, {});
/* returns
Object { 1: "Australia", 2: "United States", 3: "Brazil" }
*/
替代 .reduce 使用下划线:
var longnames = _.reduce(["India", "Australia", "United States", "Brazil"],
function( ret, name, idx ){
if( name.length > 5 ){
ret[ idx ] = name;
}
return ret;
}, {});
关于javascript - 使用Underscore获取满足特定条件的元素的所有索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34255573/