find array helper in javascript
Explore our JavaScript category, where you’ll find loads of helpful articles and tutorials for everyone, whether you’re just starting out or a pro developer. Learn about different JavaScript functions that can be used in various projects according to their specific requirements.
1- Array Initialization:
<script>
var users = [
{ name: 'jill' },
{ name: 'alexi', id: 4 },
{ name: 'bill' },
{ name: 'alex' }
];
</script>
var users = [
{ name: 'jill' },
{ name: 'alexi', id: 4 },
{ name: 'bill' },
{ name: 'alex' }
];
</script>
An array named users is created, containing objects with ‘name’ properties.
2- Traditional For Loop:
<script>
var user;
for(var i = 0; i < users.length; i++) {
if(users[i].name === 'alex') {
user = users[i];
break;
}
}
</script>
var user;
for(var i = 0; i < users.length; i++) {
if(users[i].name === 'alex') {
user = users[i];
break;
}
}
</script>
This loop iterates through the array elements and assigns the user object with the name ‘alex’ to the variable user. The loop breaks as soon as a matching user is found.
3- Logging the Result:
<script>
console.log(user);
</script>
console.log(user);
</script>
The found user object is then logged to the console.
4- Array.prototype.find() Method:
<script>
var findUser = users.find(function(user){
return user.name === 'alex';
});
</script>
var findUser = users.find(function(user){
return user.name === 'alex';
});
</script>
The Array.prototype.find() method is used to find the first element in the array that satisfies the provided testing function. In this case, it looks for a user with the name ‘alex’.
5- Logging the Result:
<script>
console.log(findUser);
</script>
console.log(findUser);
</script>