Skip to main content
  1. About
  2. For Teams
Asked
Viewed 4k times
1

I am new to javascript. This is my codes, I want it to return true if it finds 'anna' in the list

var userList = [{'username':'anna','email':'[email protected]'},
               {'username':'benny','email':'[email protected]'},
               {'username':'kathy','email':'[email protected]'}]

return userList.includes('anna')

your help it much appreciated

0

2 Answers 2

6

Use some:

ES6 syntax:

return userList.some(user => user.username === 'anna');

ES5 syntax:

function hasAnna(user) {
  return user.username === 'anna';
}
return userList.some(hasAnna);
Sign up to request clarification or add additional context in comments.

2 Comments

.some() is cool, just note that IE does not support Arrow functions.
@PHPglue good point. I've updated the answer. I kind of assume that everyone uses babel these days :-)
2

Try:

return userList.filter(function(e,i) { return e.username == 'anna' }).length > 0;

What this is doing is filtering the array, userList, for all entries with a username value of 'anna' and returning whether or not that filtered list has a length greater than 0 (i.e. has at least one entry).

2 Comments

While this will work, it's a bit inefficient... Imagine that you have a long list of thousand of items and there is one item that contains 'anna' in the second position. The solution that you are suggesting will iterate through all the items (even if 'anna' was found in the second position). Using some the execution will stop at the second one. I'm giving you a plus one anyways because your answer solves the problem.
Wouldn't a strict comparison using === be more fitting in this case?

Your Answer

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.