How can I check an array for the first occurence where a field matches using _lodash?

邮差的信 提交于 2019-12-12 01:12:13

问题


I'm currently using the following:

   for (var i = 0; i < x.length; i++)
      if (x[i].id === userId)
         return x[i].name;

This returns the user name.

Is there a more efficient way to do this using Lo-Dash? Note that the id is unique so if found there's no need to check more.


回答1:


Is there a more efficient way to do this using _lodash?

No. You can't get much more efficient than a plain old native for loop. But you can do it in less code with lodash.

You can use _.where (note that it returns a new array, rather than an object):

return _.where(x, { id: userId})[0];

But it's going to be less efficient than your code since it won't stop checking when it finds the first occurrence. It's just slightly shorter to type. You really shouldn't need to care about how efficient a simple loop is.




回答2:


var i = x.length;

while ( i--)
  if (x[i].id === userId)
  {
     return x[i].name;
     break;
  }

This is the most efficient way to loop over an array of objects. First of all you dont check the length of the array each iteration. Second of all when you find your item you break the loop.

EDITED: If you don't care about the order of the traversal start from the back, it's even faster.



来源:https://stackoverflow.com/questions/21305143/how-can-i-check-an-array-for-the-first-occurence-where-a-field-matches-using-lo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!