47

我想实现类似_.firstwith的东西_.filter,也就是说,拥有一组元素,我想获得与真值测试(迭代器)匹配的第一个(如果存在)。

例如,给定一个如下所示的数组:

var arr = [{a: 1}, {a: 5}, {a: 9}, {a: 11}, {a: 15}]

我想获得与我的自定义函数匹配的第一个(也是唯一一个)元素:

_.filterFirst(arr, function(el) { return el.a > 10; }); // make it

至今:

_.first(arr) == {a:1}
_.filter(arr, function(...)) == [{a:11}, {a:15}]

有没有比这更好的干净解决方案_.first(_.filter(arr, iterator))

4

4 回答 4

85

您可以使用find

查看列表中的每个值,返回第一个通过真值测试(迭代器)的值,如果没有值通过测试,则返回 undefined。该函数在找到可接受的元素后立即返回,并且不遍历整个列表。

使用您的示例:

var g = _.find(arr, function (x) { return x.a > 10 })

见主页:http ://underscorejs.org

另一件需要注意的事情(这可能是您的问题)是将chain呼叫连接在一起的功能:

var g = _.chain(arr).filter(function (x) { return x.a > 10 }).first().value()

请注意对和 `first' 的调用,filter它们可以在没有任何嵌套的情况下相互跟随。

于 2013-10-21T14:52:37.293 回答
0

“_.find”是一个很好的解决方案。

另一种可能更快的解决方案是以这种方式使用“Array.prototype.every”:

var match;
arr.every(function(x) { if (x.a > 10) { match = x; return false;} return true; })
于 2013-11-05T21:14:37.287 回答
0

_.find - 在 lodash 中: https ://lodash.com/docs/4.17.10#find

var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];

_.find(users, function(o) { return o.age < 40; });
// => object for 'barney'

// The `_.matches` iteratee shorthand.
_.find(users, { 'age': 1, 'active': true });
// => object for 'pebbles'

// The `_.matchesProperty` iteratee shorthand.
_.find(users, ['active', false]);
// => object for 'fred'

// The `_.property` iteratee shorthand.
_.find(users, 'active');
// => object for 'barney'
于 2018-08-29T15:48:26.990 回答
0

添加标准的 JavaScript Array.prototype.find方法,因为只是旧的答案会让新手不了解:

const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found); 
// expected output: 12

该示例来自上面链接的 MDN 页面。还有一种Array.prototype.findIndex方法可以返回谓词产生 true 的位置的索引,而不是该索引的数组元素。

这些方法在 ES2015 中。5 岁,几乎可以在人们使用的所有浏览器中使用,请参阅此caniuse 链接

于 2021-01-22T00:12:32.320 回答