.find() items and indexes in in array in 2.4 minutes…
Hello subscribers new and old, I'm very excited to be posting another newsletter to you all, I hope it's informative and useful. Please remember to spread the word about "The Coding Apprentice"!
This week we will be taking a look at the Javascript array methods “.find()” and “.findIndex()”. These simple methods allow us to iterate over an array and return an item or index we are looking for, if it exists that is!
What is an array?
For those that are not familiar, an array is a data structure used to store a collection of values and elements. These values can be of various data types, such as numbers, strings, objects, or even other arrays.
In JavaScript, an array is created using square brackets []
, and elements within the array are separated by commas. Here's a basic example of how you might create an array and populate it with some values:
// Creating an array with some values
var fruits = ["apple", "banana", "orange", "grape"];
// Accessing elements in the array
console.log(fruits[0]); // Outputs: "apple"
console.log(fruits[2]); // Outputs: "orange"
We refer to each value in an array as an “item” and it’s position as an “index”. Arrays in JavaScript are zero-indexed, which means the first element is accessed using index 0
, the second element with index 1
, and so on.
Arrays also come with a variety of built-in methods and properties that allow operations to be performed, as mentioned today we will be discussing methods that allow us to find items or indexes in our array.
.find()
This method searches through an array and returns the first item that meets the user defined condition. The condition is defined by a function passed to the method as an argument, this function should return a boolean (“true” or “false”).
The array is then cycled through, with each item in the array passed as an argument to the methods argument function. The first item that returns “true” will be the value returned from the method. If no value returns true, “undefined” with be returned.
const numbers = [7, 10, 8, 40, 5];
const evenNumber = numbers.find(number => number % 2 === 0);
console.log(evenNumber); // Output: 10
------------------------
const numbers = [7, 13, 21, 27, 33];
const evenNumber = numbers.find(number => number % 2 === 0);
console.log(evenNumber); // Output: undefined
The above implementations of the .find() method exemplify the methods functionality. The passed function argument to the method evaluates whether each item is even by assessesing whether the remainder operator returns 0 when 2 is run against it. The first example displays the first number that meets the condition “10” being returned. The second example returns “undefined” as none of the items are even, therefore the passed argument function never returns true.
A use-case example of the .find() method could be to locate a specific user in a database.
const users = [
{ id: 1, username: 'alice', role: 'user' },
{ id: 2, username: 'bob', role: 'admin' },
{ id: 3, username: 'carol', role: 'user' }
];
const targetUsername = 'bob';
const user = users.find(u => u.username === targetUsername);
console.log(user); // Output: { id: 2, username: 'bob', role: 'admin' }
The above snippet exhibits the .find() method iterating through an array of objects and identifying a user by the username key. The method then returns the first object that has a username value that matches the value of our targetUsername value.
.findIndex()
The .findIndex() method is similar to the .find() method, the only difference is that it returns the index of the first item that meets the given condition. Like .find()
, it takes a function as an argument, although it returns the index of the first matching element that returns true, not the item. If none of the evaluated items return “true”, the method returns “-1”. It’s often used when you need to find the position of a certain element within an array.
const fruits = ['apple', 'banana', 'grape', 'orange'];
const index = fruits.findIndex(fruit => fruit === 'grape');
console.log(index); // Output: 2
-----------------
const fruits = ['apple', 'banana', 'grape', 'orange'];
const index = fruits.findIndex(fruit => fruit === 'kiwi');
console.log(index); // Output: -1
A practical example of the .findIndex() method could be utilising it to identify the first unread message in a chat application.
const messages = [
{ id: 1, content: 'Hello!', read: true },
{ id: 2, content: 'How are you?', read: false },
{ id: 3, content: 'Did you watch the game?', read: false }
];
const unreadIndex = messages.findIndex(msg => !msg.read);
console.log(unreadIndex); // Output: 1
The above snippet iterates over an array of message objects and identifies the first object that has a “read” key value of false. The index of this object “1” is then returned. As a reminder, arrays in JavaScript are zero-indexed meaning we start counting our indexes at 0, therefore the second object’s index is returned as 1.
Thanks for reading, please comment or reach out with any queries, thoughts, criticism or banter.