Basics of Javascript · Array · find() (method)
This article is a transcript of my free youtube series about basics of web development. If you prefer watching over reading, feel free to visit my channel “Dev Newbs”.
Hello there my fellow developers! Who do you call when you lose something? Well, I call my mom or my wife, but in case it has to do anything with the programming in JavaScript, I have another option and that is the method find(). If there is a piece of code that can find something for you, it’s this Array object method. So let’s check how it works!
The method find() returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
As usual, the method has a callback function as an argument. This can be an arrow function or standard old-fashioned function, but it should have at least one mandatory argument, which is the element we are searching for. Optionally it can also provide an index which will represent the current element being processed and the third one is the array the method was called upon. Let’s check out the basic usage of the method.
// Example 1
// basic usage
console.log("EXAMPLE 1");
console.log("--------------------------------------------------");
let greetings = ["hello", "ola", "ciao", "hallo", "konichiwa", "ni hao", "namaste"];
// find first greeting longer than 6 characters
console.log(greetings.find((word) => word.length > 6));
// returns "konichiwa"
let numbers = [11,164,785,325,4126,98,7,4,5,62,247];
function myCustomCondition(element, index){
if((element > 200) && (index % 2 == 1))
return true;
return false;
}
// get element > 200 with odd index
console.log(numbers.find(myCustomCondition));
// returns 325
let charSequence = ["a", "b", "d", "c" , "g", "f"];
function checkAscencion(element, index, array){
if(index == 0)
return false;
if(element > array[index - 1])
return false
return true;
}
// find first element not ascending
console.log(charSequence.find(checkAscencion));
// returns "c"
The basic examples cover using the method in a typical scenario. No exceptions or edge cases here. First call to the method on an array with greetings gets us the first element that is longer than 6 characters.
The second call to method uses both element and index and it returns the first element that is greater than 200 while its index is odd.
The third call utilizes all three arguments and it checks for a first element in the array that is smaller than the previous one. With the last example, we are able to check two things — whether the sequence of elements in an array fulfills the given condition fully — we get the result of undefined — or if not, what is the element that breaks the given rules.
The array we work with does not have to consist only of primitive values. The second example set will show you that we can easily work with objects as well.
// Example 2
// working with objects
console.log("EXAMPLE 2");
console.log("--------------------------------------------------");
let fruits = [
{ name: "apple", sweetness: 5 },
{ name: "strawberry", sweetness: 7 },
{ name: "lemon", sweetness: 0 }
];
function isReallySweet(element){
if(element.sweetness > 5)
return true;
return false;
}
// find first fruit with sweetness greater than 5
console.log(fruits.find(isReallySweet))
// returns { name: "strawberry", sweetness: 7 }
// the same principle, but with arrow function and destructuring
console.log(fruits.find( ({ sweetness }) => sweetness < 4));
// returns {name: 'lemon', sweetness: 0}
Both examples deal with an array that contains 3 objects representing three different types of fruits. Each item has two properties — name and sweetness.
In the first example, we are using a typical function. Our function checks the sweetness of a given element and if it is greater than 5 it returns true. The given object is returned.
The second example shows how to achieve the same thing, but this time using the arrow function and destructuring to get the sweetness property directly without having to call the object itself. The second example searches for the first item with sweetness less than 4.
The next section will show how the find() method handles sparse arrays. Spoiler alert — empty slots are visited and are treated just like undefined value. Let’s make sure it is really like that in the next block of code.
// Example 3
// sparse arrays
console.log("EXAMPLE 3");
console.log("--------------------------------------------------");
let myArray = [1, 0, , , 84, 14, , 123];
// show each iteration using arrow function without return value
myArray.find((element, index) => {
console.log(`Element at position [${index}] has value: ${element}`);
});
Okay, I am going to admit that I cheated a little bit in this example. The point of the find() method is to find something, but I did not search for anything in my method. I just iterated through all items to showcase that even the undefined and empty slots are included.
If your consciousness does not let you do what I did, you can always include the condition at the end where you look for the last element of the array.
Last exercise of the day will deal with our favorite array-like objects and their behavior with method find(). Let’s check it out.
// Example 4
// array-like object
console.log("EXAMPLE 4");
console.log("--------------------------------------------------");
const arrayLike = {
length: 3,
0: "k",
1: "i",
2: "d",
3: "s"
};
function checkDescencion(element, index, array){
if(index == 0)
return false;
if(element < array[index - 1])
return false
return true;
}
// find char larger that previous one in an array
console.log(Array.prototype.find.call(arrayLike, checkDescencion));
// returns undefined
arrayLike.length = 4
// find char larger that previous one in an array
console.log(Array.prototype.find.call(arrayLike, checkDescencion));
// returns "s"
Just like with any other Array method, the length property is the ultimate guide on the range of available numeric properties. So only the indexes 0, 1 and 2 are taken into consideration. And since each of them is less than the previous one, our find method does not find anything. But try to change the length value and suddenly the condition function finds the culprit who is larger than its predecessor. It is the value “s”.
Okey dokey, that’s all my dear folks. I have exhausted all the examples and special cases that crossed my mind. I am sure there’s much more, but you will have to explore them on your own. As always, thanks so much for spending time with me and I will see you with the next Array method in a jiffy.