JavaScript Glossary - Lesson #1

JavaScript Array .find() Method

The find() method searches through an array and gives you 1 item based on your provided test. Array find() only returns one item. If you want to get more than one item, look at filter().

Here we'll find one person based on their name:

javascript
['chris', 'nick', 'kap'].find(function(name) {
  return name === 'kap';
});

// or simplified with es6 arrow functions
['chris', 'nick', 'kap'].find(name => name === 'kap');

You can also filter through an array of objects:

js
const people = [
  { name: 'chris', username: 'chris__sev' },
  { name: 'nick', username: 'whatnicktweets' },
  { name: 'kapehe', username: 'kap' },
];

people.find(person => person.name === 'kapehe');
// output: { name: 'kapehe', username: 'kap' }
javascript
const foundItem = myArray.find(callbackFunction);

callbackFunction (function)

The function to execute over each of the elements of the array. When the function returns true , it has found its item.

The callback function takes 3 parameters.

  • element: this is the element currently being executed - required.
  • index: the index of the current item - optional.
  • array: the array that is currently being processed - optional.

thisArgument (this) (optional)

We can also pass an argument as the second parameter to be used as the this value in the callback

Array find() will return the single item that it finds. This can be a string, object, or any item in the array.

We'll look through this list and find() the first number that is less than 50. Array find() only returns one item. If you want to get more than one item, look at filter().

js
const numbers = [60, 32, 55, 22, 10];
const lessThan50 = numbers.find(number => number < 50 );

console.log(lessThan50);
// output: 32

With the find() mthod we can fetch an array item using a specific index value of the item.

js
const items = ['nail', 'hammer', 'bolt'];

// find array item with index of 1
const atIndex = items.find(function(element, index){
  return index === 1
})

// display array item found
console.log(atIndex)

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)