问题
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