【发布时间】:2015-11-15 15:07:56
【问题描述】:
给定一个对象数组,我正在尝试编写一个方法,该方法可以获取某个项的索引,其中特定属性的值在数组中已出现n 次。
这段代码可能更容易描述我想要实现的目标:
var foods = [
{
name: "orange",
owner: "bob"
},
{
name: "carrot",
owner: "fred"
},
{
name: "apple",
owner: "bob"
},
{
name: "onion",
owner: "fred"
},
{
name: "banana",
owner: "bob"
},
{
name: "pear",
owner: "bob"
}
];
function getIndex(owner, nthItem){
// solution code
}
getIndex("bob", 3); // should return 4 as it is the index of bob's 3rd item in foods
我更喜欢格式良好的下划线/lodash 解决方案,而不是 20 多行纯 JS 解决方案。如果你能用纯 JS 做更少的事情,那很好。
我已经尝试使用 _.groupBy 和 _.pluck 来获取各个列表,但找不到将这些信息从原始数组转换回索引的方法。
【问题讨论】:
-
nthItem应该从1开始?或者可以是0? -
nthItem应该从1开始,但它返回的索引应该从0开始。
标签: javascript arrays underscore.js lodash